0

问题:

我正在创建一个 HTML5 画布游戏,我想为我的船创建一个对象,将船的 src 分配给 images/powship.png。如果我创建船然后为 i 变量分配一个 src,它会起作用,但我想知道在我建造船时是否可以一次完成所有操作。

如果我做这样的事情有效:

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"
    }
}

但这似乎不起作用。

有效的代码在这里

演示在这里

未缩小的 JS 文件

问题:

如何在创建对象时运行函数?

4

3 回答 3

2

该函数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();

或者你可以这样咖喱:

var ship = function(){
    result = {
       x : $(window).height()/2,
       y : $(window).height()/2,
       i : new Image()
    }
    result.i.src = "images/powship.png";
    return result;
};
于 2012-07-10T01:13:30.310 回答
1

您应该创建一个构造函数,它可以让您重用代码。

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();

你不能做你想做的事情,因为对象在你创建它之后才存在,所以你不能在用文字符号创建它时引用它的属性。

于 2012-07-10T01:21:13.507 回答
-1
i : new Image({src : "images/powship.png" })

试试看,应该可以的。

于 2012-07-10T01:14:03.493 回答