Javascript 如何在创建对象时运行函数? 问题:
我正在创建一个HTML5画布游戏,我想为我的飞船创建一个对象,将飞船的src分配给images/powship.png。如果我创建一艘飞船,然后给I变量赋值一个src,它就可以工作了,但是我想知道,当我建造飞船的时候,我是否可以一次完成这一切 如果我这样做,效果会更好:Javascript 如何在创建对象时运行函数? 问题:,javascript,jquery,canvas,Javascript,Jquery,Canvas,我正在创建一个HTML5画布游戏,我想为我的飞船创建一个对象,将飞船的src分配给images/powship.png。如果我创建一艘飞船,然后给I变量赋值一个src,它就可以工作了,但是我想知道,当我建造飞船的时候,我是否可以一次完成这一切 如果我这样做,效果会更好: ship = { //a class for my ship x : $(window).width()/2, y : $(window).height()/2, i : new Image() } sh
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"
}
}
var ship = function(){
result = {
x : $(window).height()/2,
y : $(window).height()/2,
i : new Image()
}
result.i.src = "images/powship.png";
return result;
};
当我创建我的飞船时,我想一次完成这一切(把东西放在一起)。大概是这样的:
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"
}
}
var ship = function(){
result = {
x : $(window).height()/2,
y : $(window).height()/2,
i : new Image()
}
result.i.src = "images/powship.png";
return result;
};
但它似乎不起作用
问题:
如何在创建对象时运行函数?函数
ship.src()代码>未运行,这就是为什么未设置.src
的原因
您的ship类可能希望在创建时运行更多的东西,因此构造函数是合适的
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();
或者你可以这样做:
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"
}
}
var ship = function(){
result = {
x : $(window).height()/2,
y : $(window).height()/2,
i : new Image()
}
result.i.src = "images/powship.png";
return result;
};
试试看,应该可以。你应该创建一个构造函数,让你可以重用代码
function Ship() {
var win = $(window);
this.x = win.width()/2;
this.y = win.height()/2;
this.i = new Image();
this.src = this.i.src = "images/powship.png";
}
var ship1 = new Ship();
var ship2 = new Ship();
你不能做你想做的事情,因为这个对象在你创建它之前是不存在的,所以你不能在用文字符号创建它的时候引用它的属性。我考虑过这个问题,但我真的只需要一艘船,因为它是主角。我想我可以对不同类型的船只使用同一个构造函数,然后使用这个构造函数。@user1460419那么我的curry示例可能更合适。我只是想知道是否可以在一个对象内同时完成所有操作。不过这看起来非常好。谢谢你的帮助。我可能会选择一些构造器选项,但我只是想知道是否可以一次性完成有时候最简洁的方式并不总是最好的。如果你像在你的第一段代码中那样把它放在单独的一行中,阅读起来会更容易。是的,但它更像是一个……我能做这个问题吗?I:{src:{images/powship.png}
,然后当你创建或更新飞船时,你可以调用new Image(ship.I.src)
i:$(新图像).attr('src','images/powship.png')
没有jQuery,i:(新图像).setAttribute('src','images/powship.png')