const obj = {
_name: '0',
get aaa() {
console.log('123')
return this._name
},
set aaa(val) {
this._name = val
}
}
console.log("TCL: obj.aaa", obj.aaa)
obj.aaa = 2
console.log("TCL: obj", obj)
const obj1 = {
_name : '2'
}
Object.defineProperty(obj1,'name',{
get: function(){
return this._name
},
set: (val)=>{
this._name = val
}
// set: function(val){
// this._name = val
// }
})
Object.defineProperty(obj1,'age',{
value: 19,
enumerable: true
})
obj1.name = 3
console.log('obj1._name',obj1)
for (let i in obj1){
console.log('i',i)
}
程序作用是老师给我们讲解如何在ES5实现get和set方法,注意注释部分,我注释掉的代码是可以正确运行的,但是上面的ES6写法的SET却不行,还提示_name从未被使用,我觉得很奇怪,如果成功的话下obj1里的_name的值会被改变