问题:
我正在创建一个 HTML5 Canvas 游戏,我想为我的船创建一个对象,将船的 src 分配给 images/powship.png。如果我创建船舶然后为 i 变量分配一个 src,它就可以工作,但我想知道在 build 船舶时是否可以一次性完成所有操作。
如果我这样做就可以工作:
ship = { //a class for my ship
x : $(window).width()/2,
y : $(window).height()/2,
i : new Image()
}
ship.i.src="images/powship.png";
当我创建我的飞船时,我想一次性完成这一切(以将所有东西保持在一起)。像这样的事情:
ship = { //a class for my ship
x : $(window).width()/2,
y : $(window).height()/2,
i : new Image(),
src : function() {
return this.i.src="images/powship.png"
}
}
但似乎不起作用。
问题:
如何在对象创建时运行函数?
最佳答案
函数ship.src();
未运行,这就是.src
未设置的原因。
您的飞船类可能需要在创建时运行更多东西,因此构造函数是合适的。
var Ship = function(){
// set up basic components of your class
this.x = $(window).width()/2;
this.y = $(window).height()/2;
this.i = new Image();
// preform any construction requirements
this.i.src = "images/powship.png";
};
var ship = new Ship();
或者你可以像这样 curry :
var ship = function(){
result = {
x : $(window).height()/2,
y : $(window).height()/2,
i : new Image()
}
result.i.src = "images/powship.png";
return result;
};
关于javascript - 如何在对象创建时运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11405332/