我有这个对象变量:
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"
虽然它适用于正常情况:
函数名() {}
var test_var = 新名称()
所以我的猜测是"new"仅适用于功能。但是我怎样才能像以前那样使用可变对象呢? (我想在一个数组中包含多个,而不仅仅是对一个对象的多个引用)
最佳答案
在 ES5 及以下版本中,您可以创建一个充当构造函数的函数。在内部使用 this
将属性绑定(bind)到从 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);
关于javascript - 如何使用 "new"将对象变量添加到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860869/