【发布时间】:2011-09-21 04:04:26
【问题描述】:
我目前正在将我的一个 java 小程序游戏移植到 javascript+html5。我以前从未做过面向对象的 javascript,这个基于原型的 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...
}
请大家帮忙!
【问题讨论】:
标签: javascript oop canvas prototype-programming