我目前正在將我的一個java applet遊戲移植到javascript + html5。我從來沒有做過面向對象的JavaScript,而這個基於OO的原型讓我很困惑。將參數添加到javascript對象
我試着做從Java一個簡單的端口,但我有麻煩做兩件事情:
1)如何運行一個構造函數中的功能?
2)如何添加一個有參數的方法?
繼承人一些示例代碼:
function User()
{
setupStats();// I wanted to put some of the variable initializations into
// a separate function for code modularity reasons.
this.name='bob';
//However that doesn't seem to work
alert(this.gold); // gets Undefined
alert(this.name); // gets bob. Phew at least this works
//I also want to add a method with a parameter in it:
this.draw=function(ctx){drawUser(ctx);};
}
function setupStats()
{
this.gold=2;
this.exp=3;
this.blah='blah';
this.that='something else';
this.superultraomg='insert some computation';
}
function drawUser(ctx)
{
ctx.drawImage(blah,blah,blah);
alert(ctx); // Also gets undefined. Uh oh...
alert(this.name); //Undefined? WHAT IS THIS I DONT EVEN...
}
請幫傢伙!
你測試過了嗎?看起來像一些語法錯誤給我。 – awm
沒有。我只是想給他一些關於函數原型的想法,以及'this'關鍵字的範圍如何受到影響。隨意推薦編輯以使代碼更加複製/粘貼友好。 – fdfrye
我最喜歡這種添加方法的方式(因爲它讓我的移植工作更容易,因爲它最容易讓人聯想到基於Java的基於類的OO)。但是,您的user.init = function()應該是user.prototype.init = function()。答案接受:)具有編輯權限的人可以修復語法錯誤嗎? –