题解 | #监听对象#
监听对象
https://www.nowcoder.com/practice/2cd8f8421e9b42b98152f56ef5e0ac79
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <style> ul { list-style: none; } </style> <ul></ul> <script> var ul = document.querySelector('ul'); var person = { sex: '男', age: '25', name: '王大锤', height: 28, weight: 32 }; const _render = element => { var str = `<li>姓名:<span>${person.name}</span></li> <li>性别:<span>${person.sex}</span></li> <li>年龄:<span>${person.age}</span></li> <li>身高:<span>${person.height}</span></li> <li>体重:<span>${person.weight}</span></li>` element.innerHTML = str; } _render(ul); // 补全代码 //创建函数对目标对象进行数据拦截 function Observe(target){ //判断传入的目标对象是否是合法对象 if(typeof target !== 'object' || target == null){ return target; } //对目标对象的key值进行遍历 for (var key in target){ defineReactive(target,key,target[key]) } } //创建监听目标对象数据修改的函数 function defineReactive(target,key,value){ Object.defineProperty(target,key,{ get: function(){ return value }, set: function(newValue){ if(newValue !== value){ value = newValue } _render(ul); } }) } Observe(person) </script> </body> </html>此题主要是对Object.defineProperty()方法考察