我有这个对象变量:
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())
但它引发了一个错误:
“未捕获的TypeError:背景不是构造函数”
虽然它可以正常使用:
function name() {}
var test_var = new name()
所以我的猜测是“新”仅适用于功能。但是我如何使用之前的变量对象呢? (我希望在一个数组中有多个,而不只是对一个对象的多个引用)
答案 0 :(得分: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);