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的值会被改变
https://blog.csdn.net/qq_42926749/article/details/82971872
箭头函数(val)=>{}内没有自己的this。
如果在箭头函数内使用this,访问的是箭头函数外层作用域的this。
你这个代码箭头函数外层作用域是 window全局作用域 ,this指向的是window对象。
所以对象的方法不要用箭头函数。