<script>
var x = 0
Object.defineProperty(this, 'a', {
get() {
x++
console.log('get');
return x
}
})
console.log(a === 1 && a === 2 && a === 3);
var obj = {
}
Object.defineProperty(obj, 'name', {
get() {
console.log('get');
}
})
name //无打印
obj.name //打印 'get'
//结论:Object.defineProperty(obj, 'name')会创建name属性加入到obj,并且监听obj.name;并不能监听name
var obj = {
name: 1
}
console.log(obj.name); //1
Object.defineProperty(obj, 'name', {
get() {
console.log('get'); //'get'
}
})
console.log(obj.name); //undefined
//打印依次为1,'get',undefined 最后一行代码'console.log(obj.name)'读取obj.name被get劫持并且get无返回值,因此undefined
var obj = {
name: 1
}
console.log(obj.name); //1
Object.defineProperty(obj, 'name', {
get() {
console.log('get'); //'get'
return 10
}
})
console.log(obj.name); //10 最后一行代码'console.log(obj.name)'读取obj.name被get劫持并且get返回值为10替代了obj.name
</script>