Javascript原型属性与数组和对象字段无法正常工作 [英] Javascript prototype property not working as expected with array and object fields

查看:145
本文介绍了Javascript原型属性与数组和对象字段无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码得到意外结果:

I get an unexpected result with the following code:

var TestModel, u, u2;

function TestModel() {}
TestModel.prototype.a = null;
TestModel.prototype.b = [];

u = new TestModel();
u.a = 1;
u.b.push(1);

u2 = new TestModel();
u2.a = 2;
u2.b.push(2);

console.log(u.a, u.b);     // outputs: 1 [1,2]
console.log(u2.a, u2.b);   // outputs: 2 [1,2]

我发现令人惊讶ub u2.b 包含相同的值,即使每个 TestModel 的实例都应该有根据我如何设置原型,它自己的实例变量。所以这是我期待的输出:

I find it surprising that u.b and u2.b contain the same values even though each instance of TestModel should have its own instance variables according to how I've setup the prototype. So this is the output I was expecting:

console.log(u.a, u.b);     // expecting: 1 [1]
console.log(u2.a, u2.b);   // expecting: 2 [2]

如果我设置同样的事情发生b 成为一个对象并在其上设置键而不是将其用作数组。我在这里不理解的是什么?

The same thing happens if I set b to be an object and set keys on it rather than using it as an array. What am I not understanding here?

推荐答案

分配值与之间存在差异引用它们。

u.a = 1;

将创建一个新的 a 属性 u 引用的对象。在分配之前, ua 将引用 TestModel.prototype.a ,但是分配新值实际上会创建一个新属性在实际对象上:

will create a new a property on the object referred to by u. Before the assignment, u.a will refer to TestModel.prototype.a, but assigning a new value actually creates a new property on the actual object:

作业完成后:

另一方面,

u.b.push(1);

创建新属性。它将引用现有属性,数组, TestModel.prototype.b

will not create a new property. It will reference the existing property, the array, which is TestModel.prototype.b.


即使每个 TestModel 的实例都应该有我自己的实例变量,这取决于我如何设置原型

even though each instance of TestModel should have its own instance variables according to how I've setup the prototype

所有实例都引用相同的原型,因此它们引用了原型所具有的相同属性。你可以很容易地看到,因为 TestMode.prototype === ub TestMode.prototype === u2.b ub === u2.b 所有收益 true

All instances reference the same prototype, hence they reference the same properties the prototype has. You can easily see that because TestMode.prototype === u.b, TestMode.prototype === u2.b and u.b === u2.b all yield true.

如果您为 ub u2分配一个新值,它也会有效。 b 以及:

u.b = [];

通常在构造函数中完成:

which is normally done in the constructor:

function TestModel() {
    this.b = [];
}

这篇关于Javascript原型属性与数组和对象字段无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆