[英]Javascript: All Objects in Array Have Same Properties
I am trying to create a list of objects that are listed in an array. 我正在尝试创建数组中列出的对象列表。 newConstant is a function that creates the objects and them pushes them to the array. newConstant是一个创建对象并将其推入数组的函数。 However, when the while loop runs through the array and throws up alerts containing one of the properties of each array, it spits out the value for the last object for each object in the array. 但是,当while循环遍历数组并引发包含每个数组属性之一的警报时,它将为数组中的每个对象吐出最后一个对象的值。 In this situation it alerts "3" each time, but it should alert "1", then "3", as those are the value of the property x for the two objects in the array "a". 在这种情况下,它每次都会警告“ 3”,但是应该警告“ 1”,然后警告“ 3”,因为这是数组“ a”中两个对象的属性x的值。 The code is below. 代码如下。 How can I fix this? 我怎样才能解决这个问题?
var i = 0;
var a = [];
var newConstant = function (x, y) {
this.x = x;
this.y = y;
a.push(this);
};
var one = newConstant(1, 2);
var two = newConstant(3, 4);
while (i < a.length) {
alert(a[i].x);
i++;
}
You're written newConstructor
as a constructor but you're using it as a normal function, try adding the new
keyword. 您将newConstructor
编写为构造函数,但是将其用作常规函数,请尝试添加new
关键字。
var i = 0;
var a = [];
var newConstant = function (x, y) {
this.x = x;
this.y = y;
a.push(this);
};
var one = new newConstant(1, 2); //notice the new keyword indicating a constructor
var two = new newConstant(3, 4);
while (i < a.length) {
alert(a[i].x);
i++;
}
Here it is in action: http://jsfiddle.net/V3zwW/ 它在起作用: http : //jsfiddle.net/V3zwW/
Here is an article about the this keyword in javascript . 这是有关javascript中this关键字的文章。 Here is another reference on how to correctly use the Constructor pattern 这是有关如何正确使用构造器模式的另一参考
What happened before is that your second call set this.x
to 3 However this
referred to the window
, this is because functions in javascript assign this to their caller unless they are constructors. 之前发生的是您的第二次调用将this.x
设置为3。 this
引用到window
,这是因为javascript中的函数将其分配给调用方,除非它们是构造函数。 In your case you alerted window.x
(which you set to 3) two times resulting in 3 3
在您的情况下,您window.x
警告window.x
(您将其设置为3)导致3 3
you have forgotten about the keyword "new", see the example below: 您忘记了关键字“ new”,请参见以下示例:
var one = new newConstant(1, 2);
var two = new newConstant(3, 4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.