2015-07-09 40 views
0

在一定程度上我知道什麼在代碼中發生的事情,只是爲了澄清我的懷疑我已經發布了這個問題此關鍵字匿名函數內部/構造

的JavaScript

Point = function (x, y)  //Here anonymous constructor is define 
{ 
    this.x = x; 
    this.y = y; 
} 

var points=[] 
points.push(new Point(centerX + radius * Math.sin(angle),centerY - radius * Math.cos(angle))); //object is created and push in the array 

以及訪問點的值數組,我可以寫點[i] .x?

+0

是的,正是。 'this'關鍵字只是一個自我引用。如果你將'console.log(points)'添加到你的JavaScript中,你可以看到你的對象的結構,以更好地理解底下發生了什麼。 – Jason

+0

「我可以寫點[i] .x」 - 測試如何? – Johan

+0

構造函數是匿名的並不重要。儘管如此,使用'函數Point(x,y){...}'本來是一個好習慣。 – Bergi

回答

0

是的,看看這個

var Point = function (x, y)  //Here anonymous constructor is define 
{ 
    this.x = x; 
    this.y = y; 
} 

var points = []; 
points.push(new Point(2,5)); 
points.push(new Point(3,11)); 
points.push(new Point(9,1)); 

for(var i = 0; i <points.length; i++){ 
console.log(points[i].x); 
console.log(points[i].y); 
}; 
0

正確的,你可以使用它的索引我訪問的對象,那麼你就提領該對象來訪問它的屬性/成員

var Point = function (x, y) 
{ 
    this.x = x; 
    this.y = y; 
} 

var points = []; 
points.push(new Point(1, 2)); 
var point = points[0]; 
alert(point.x == point[0].x);