我目前正在将我的一个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...
}
请帮帮我们!
答案 0 :(得分:4)
我们正在使用原型,与setupStats
共享默认值Users
。我们正在使用call来传递上下文,User
对象和parameter
;
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...
}
答案 1 :(得分:3)
你离我太远了。麻烦主要是你使用'this'关键字。
你想要更像的东西:
var user = {};
var user.setupStats = function ()
{
this.gold=2;
this.exp=3;
this.blah='blah';
this.that='something else';
this.superultraomg='insert some computation';
};
var user.init = function ()
{
this.name='bob';
//Setup the stats
this.setupStats();
//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);};
};
你会继续这种方法并通过像
这样的事情来执行对它的调用user.init();
会自动将您的函数引用链接在一起。
答案 2 :(得分:0)
我建议阅读Douglas Crockford撰写的JavaScript: The World's Most Misunderstood Programming Language。他清楚地解释了如何在JavaScript中完成类,私有成员,公共成员,继承等。
答案 3 :(得分:0)
您可能需要考虑在类范围中包含这些方法,如果仍然存在方法歧义,则可以使用点表示法来解决命名空间歧义。 this.name有效,因为它是在同一个函数中定义的,但是其他函数不知道它们是否存在于同一个作用域中,因此它们返回undefined。
在drawUser()中未定义ctx,因为参数声明不正确。 Javascrpit params应该被称为(NB他们不接受var关键字):
function methodName( aParam : aParamType, bParam : bParamType) {}
使用class关键字[optional,omit square bracket] 声明类
[private public static] class ClassName [extends ParentClass] { /*methods here*/ }
希望这会有所帮助。