首页 > 解决方案 > Object.create 中的对象属性值是常量吗?

问题描述

这是一个非常奇怪的问题,我一直在学习一些 Javascript,并且我得到了代码,但我想了解为什么会发生这种情况:

为什么我可以让 att 和 def boost 在 Object.create 之外创建但属性 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);

标签: javascriptprototypeprototypal-inheritanceprototype-chain

解决方案


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

hp: { value: 500}

它的作用就像

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

writable: false表示该属性是只读的。

另一方面,当通过赋值创建属性时,enumerable两者writable都默认为true.

此外,请确保始终以严格模式写入,以便分配给只读属性会引发错误,而不是静默失败!


推荐阅读