我目前正在将我的一款 Java 小程序游戏移植到 javascript+html5。我以前从未做过面向对象的 JavaScript,这种基于原型(prototype)的 OO 东西让我很困惑。
我尝试从 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...
}
请大家帮忙!
最佳答案
我们正在使用原型(prototype),与所有用户
共享setupStats
中的默认值。我们正在使用 call传递一个上下文,即User
对象和一个参数
;
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.call(this, ctx); };
}
function setupStats()
{
this.gold=2;
this.exp=3;
this.blah='blah';
this.that='something else';
this.superultraomg='insert some computation';
}
User.prototype = new setupStats();
new User().draw('pinky');
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...
}
关于javascript - 将带参数的方法添加到 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7494469/