簡體   English   中英

如何在對象創建上運行函數?

[英]How do I run a function on object creation?

問題:

我正在創建一個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文件

題:

如何在對象創建上運行函數?

函數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;
};

您應該創建一個構造函數,讓您重用代碼。

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

您無法執行您要執行的操作,因為在創建對象之前該對象不存在,因此在使用文字符號創建對象時無法引用其屬性。

i : new Image({src : "images/powship.png" })

試試看,應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM