最近在看尤雨溪的vue讲课记录一下笔记。 需求:(小型数据监听器) 实现一个convert对象, 1.遍历对象的所有属性,并重新定义它的setter,getter 2.每次访问或者修改属性值都要console.log()
<script>
function isObject(obj) {
return typeof obj === "object" &&
!Array.isArray(obj) &&
obj !== null &&
obj !== undefined
}
function convert(obj) {
if (!isObject(obj)) {
throw new TypeError("Not an Object or Object is null or undefined");
}
Object.keys(obj).forEach(key => {
let internalValue = obj[key];
Object.defineProperty(obj, key, {
set(newValue) {
console.log(`setting:${key}=${newValue}`);
internalValue = newValue;
},
get() {
console.log(`getting:${key}=${internalValue}`);
return internalValue
},
})
})
}
let obj = {
name: '233',
age: 23,
};
convert(obj);
obj.age = 21;
console.log(obj);
</script>
|