var person = {
sayName() {
console.log(this.name);
},
get firstName() {
return "Nicholas";
}
};
person.sayName.name // "sayName"
person.firstName.name // "get firstName"
上面的代码是阮神的ES6一书中,但是我的运行结果person.firstName.name为undefined,因为person.firstName只是一个字符串而不是函数。
附上链接http://es6.ruanyifeng.com/#do...
还有,我按照ES6这种和ES5的get,set写出来的对象也有差异:
var cart = {
_wheels: 4,
get wheels () {
return this._wheels;
},
set wheels (value) {
if (value < this._wheels) {
throw new Error('数值太小了!');
}
this._wheels = value;
}
}
var book={
_year:4
}
Object.defineProperty(book,'year',{
get:function(){
return this._year+1
},
set:function(m){
_year = m*2;
}
})
console.log(cart);
console.log(Object.keys(cart));
console.log(Object.keys(book));
想请人帮我解答一下,谢谢了!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
还是基础只是不太牢固。
当我读取firstName时,已经通过getter函数转化成字符串了
person.firstName === 'Nicholas'所以自然而然没有
name属性了。浏览器属性还是要通过
Object.getOwnPropertyDescriptor()来获取Object.getOwnPropertyDescriptor(person, 'firstName').get.name就可以正确的获取name属性了。多谢@onioNN的解答,谢谢!
另一个问题,就是通过ES6简写的浏览器属性会被添加到可列举的属性中?