2013-02-06 155 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); 
相關問題