I've got this object variable:
我有一个对象变量:
var Background = {
x: 0,
y: 0,
speed: 4,
initialize: function (x, y){
this.x = x;
this.y = y;
move: function(){
this.x -= this.speed;
}
};
And I'd like to create new object variable and add it to an array:
我想创建一个新的对象变量并将它添加到一个数组中:
background_container = []
background_container.push(new Background())
But it throws an error:
但它犯了一个错误:
"Uncaught TypeError: Background is not a constructor"
“未捕获的类型错误:背景不是构造函数”
Although it works with normal: function name() {} var test_var = new name()
So my guess is that "new" works only for functions. But how can I do it with variable objects like the one before? (I want to have multiple of them in one array and not just multiple references to one object)
虽然它使用的是normal: function name() {} var test_var = new name(),所以我猜“new”只适用于函数。但是我怎么能用像之前那样的变量对象来做呢?(我希望在一个数组中包含多个对象,而不仅仅是对一个对象的多个引用)
1 个解决方案
#1
6
With ES5 and below you can create a function which acts as a constructor. Use this
inside to bind properties to the current object which is returned from the new
operator. Also you can leave the initalize
function (if you intend to use this only one time) and pass parameters into the function or constructor
directly.
使用ES5和下面的代码,您可以创建作为构造函数的函数。在内部使用此属性将属性绑定到从新操作符返回的当前对象。您还可以保留initalize函数(如果您只打算使用一次),并将参数直接传递给函数或构造函数。
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);
With ES6 and higher you can use Ecmascript's new syntax for creating classes.
使用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);
#1
6
With ES5 and below you can create a function which acts as a constructor. Use this
inside to bind properties to the current object which is returned from the new
operator. Also you can leave the initalize
function (if you intend to use this only one time) and pass parameters into the function or constructor
directly.
使用ES5和下面的代码,您可以创建作为构造函数的函数。在内部使用此属性将属性绑定到从新操作符返回的当前对象。您还可以保留initalize函数(如果您只打算使用一次),并将参数直接传递给函数或构造函数。
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);
With ES6 and higher you can use Ecmascript's new syntax for creating classes.
使用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);