2013-02-06 156 views
2

我正在尝试创建数组中列出的对象的列表。 newConstant是一个创建对象并将它们推送到数组的函数。但是,当while循环遍历数组并引发包含每个数组的某个属性的警报时,它会为数组中的每个对象分配最后一个对象的值。在这种情况下,它每次都会提醒“3”,但它应该提醒“1”,然后提醒“3”,因为这些是数组“a”中两个对象的属性x的值。代码如下。我怎样才能解决这个问题?Javascript:数组中的所有对象具有相同的属性

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++; 
} 
+1

阵列中的每个对象是' window'。 – zzzzBov

+0

@zzzzBov我的地址在我的回答:) –

回答

1

你写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++; 
} 

这是在行动:http://jsfiddle.net/V3zwW/

这里是一个文章关于the this keyword in javascript。这里是另一个reference on how to correctly use the Constructor pattern

发生了什么事之前,你的第二个电话设置this.x 3然而this提到的window,这是因为在JavaScript函数分配到了他们的来电者,除非他们是建设者。在你的情况,你提醒window.x(你设置为3),导致3 3

+0

谢谢!这绝对清除了我的问题。 – user2048858

0

你已经忘记了关键字“新”两次,见下面的例子:

var one = new newConstant(1, 2); 
var two = new newConstant(3, 4); 
相关问题