我目前正在将我的一个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()。答案接受:)具有编辑权限的人可以修复语法错误吗? –