繁体   English   中英

对象属性值在Object.create中是常量吗?

[英]Are object properties value constants in Object.create?

这是一个非常奇怪的问题,我一直在学习一些Javascript,并且我的代码可以运行,但是我想了解为什么会这样:

当在Object.create之外创建att和def提升但属性hp作为常量工作时,为什么可以使它们起作用?

 let Pokemon = { def: this.def, att: this.att, defBoost: function() { this.def = this.def + this.def return this.def; }, attBoost: function() { this.att = this.att + this.att return this.att; }, hpBoost: function() { this.hp = this.hp + this.hp return this.hp; } } let psyduck = Object.create(Pokemon, { name: { value: "Psyduck" }, hp: { value: 500 } }); psyduck.def = 12; psyduck.att = 20; console.log(psyduck); psyduck.attBoost(); psyduck.defBoost(); psyduck.hpBoost(); console.log(psyduck); 

当用描述符定义一个属性时(如Object.definePropertiesObject.create ,您未指定的所有属性默认都为false 所以当你有

hp: { value: 500}

它像

hp: {
    value: 500,
    enumerable: false,
    writable: false,
}

writable: false表示该属性为只读。

另一方面,在通过赋值创建属性时, enumerablewritable都默认为true

另外,请确保始终以严格模式进行写入,因此分配给只读属性会引发错误,而不是无提示地失败!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM