2017-10-21 70 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);