【问题标题】:Is it possible to add value to a new property of an object in js?是否可以在 js 中为对象的新属性添加值?
【发布时间】:2017-03-09 08:17:43
【问题描述】:

在 js 中我创建了一个对象。我想向对象的原型添加一个新属性,并且该属性将因实例而异。 现在为了增加价值,我使用了 get。但这给了我错误。我已经添加了下面的代码。

我怎样才能完成这件事?

我已经用谷歌搜索过了。我所学到的只是 get 他们为现有财产增加了价值。但我想为新属性增加价值,这会因实例而异。

var computer = function (name, ram) {
    this.name = name;
    this.ram = ram;
};

Object.defineProperty(computer.prototype, "graphic", {
    set: function graphic(value) {
        this.graphic = value;
    },
    get: function graphic() {
        return this.graphic;
    },
});

var vio = new computer("sony", "8gb");


vio.graphic = "gtx980";

console.log(vio.graphic);

错误消息:

enter image description here

【问题讨论】:

  • But it gives me error - 我们应该猜猜错误是什么?
  • 您不能将属性 getter/setter 设置为它自己的名称。使用本地变量,这在原型方法上很烦人,或者 get/set this._graphic fron this.graphic 代替
  • 错误:Out of stack space,很明显。
  • 在 Firefox 中是 too much recursion - 这应该会使问题更加明显
  • 您可以删除所有添加属性的代码。 vio.graphic = "gtx980"; 就是你所需要的。

标签: javascript object get prototype


【解决方案1】:

重读你的问题,我会回答你真正关心的问题:

当你把东西放在原型上时,它们会在所有实例之间共享(就像你用像 Java 这样的经典语言将它们添加到类中)。 当你把东西放在this 上时,它们只能被特定的实例访问。

以下工作,没有 setter 或 getter:

function Computer(name, ram) { // Please use Capital names for constructors
    this.name = name;
    this.ram = ram;
};

let vio = new Computer('sony', '8gb');
vio.graphic = 'gtx980';

graphic 属性只存在于vio 中保存的实例,而不是所有的计算机实例。

另一方面,如果您要这样做:

function Computer(name, ram) {
  this.name = name;
  this.ram = ram;
}

Computer.prototype.graphic = 'gtx980';

// All instances of Computer will now have a .graphic with the value of 'gtx980'.

您收到错误的原因是您为graphic 定义了一个setter,在其中,您试图分配给graphic,它调用graphic 的setter,它试图分配给@987654329 @ 调用....你明白了。

解决方案是更改实际变量的名称(例如 _graphic)。

var computer = function (name, ram) {
    this.name = name;
    this.ram = ram;
};

Object.defineProperty(computer.prototype, "graphic", {
    set: function graphic(value) {
        this._graphic = value;
    },
    get: function graphic() {
        return this._graphic;
    },
});

var vio = new computer("sony", "8gb");


vio.graphic = "gtx980";

console.log(vio.graphic);

请注意,JS 并没有真正的私有变量。您将无法阻止某人更改_graphic

【讨论】:

  • 我能知道它背后的理论吗?如果我打电话给console.log(Object.getOwnPropertyNames(vio));,我会得到 _graphic 而不是 graphics 作为属性。这是为什么呢?
  • 因为那是实际属性。 getter 和 setter 不是对象的实际属性,但底层的 _graphic 是。
  • @zoha131 我已经进行了编辑以解释实际问题,而不是您尝试的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2017-03-16
  • 2021-12-29
  • 2014-08-13
  • 2010-11-14
相关资源
最近更新 更多