2017-10-21 92 views
2

我有了這個對象變量:如何使用「新」將對象變量添加到數組?

var Background = { 
     x: 0, 
     y: 0, 
     speed: 4, 

     initialize: function (x, y){ 
      this.x = x; 
      this.y = y; 

     move: function(){ 
      this.x -= this.speed; 
     } 

    }; 

,我想創建新的對象變量,並將其添加到一個數組:

background_container = [] 
background_container.push(new Background()) 

但它拋出一個錯誤:

"Uncaught TypeError: Background is not a constructor"

雖然它與正常工作: function name() {} var test_var = new name() 所以我的猜測是「新」只適用於功能。但是我怎麼能用前面的變量對象來做到這一點呢? (我想在一個數組中包含多個數據,而不僅僅是多個引用到一個對象)

回答

6

使用ES5和更低版本,您可以創建一個充當構造函數的函數。使用裏面的this將屬性綁定到從new運算符返回的當前對象。您也可以離開initalize功能(如果您打算僅使用此功能)並將參數直接傳遞到功能或constructor

function Background(x, y) { 
 

 
    this.x = x || 0; 
 
    this.y = y || 0; 
 
    this.speed = 4; 
 

 
    this.move = function() { 
 
     this.x -= this.speed; 
 
    } 
 

 
}; 
 

 
var backgrounds = []; 
 
backgrounds.push(new Background(1, 3)); 
 

 
console.log(backgrounds[0].x); 
 
console.log(backgrounds[0].y);

隨着ES6和更高的可使用的ECMAScript的新語法創建類。

class Background { 
 

 
    constructor(x = 0, y = 0) { 
 
     this.x = x; 
 
     this.y = y; 
 
     this.speed = 4; 
 
    } 
 

 
    move() { 
 
     this.x -= this.speed; 
 
    } 
 

 
}; 
 

 
const backgrounds = []; 
 
backgrounds.push(new Background(1,3)); 
 

 
console.log(backgrounds[0].x); 
 
console.log(backgrounds[0].y);