javascript - 将带参数的方法添加到 javascript 对象

标签 javascript oop canvas prototype-programming

我目前正在将我的一款 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...
}

请大家帮忙!

最佳答案

Example

我们正在使用原型(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/

相关文章:

javascript - 如何将 fillPatternImage 置于楔形中心?

javascript - 如何在调整屏幕大小时使 Canvas 元素响应?

javascript - 将内容移动到 View 中而不滚动容器

javascript - 警报消息 onclick 事件

php - CodeIgniter 在同一 Controller 中加载多个模型

java - 实例级线程本地存储有什么优势?

javascript - 如何在 JQuery 中解析集合

Javascript 检查鼠标在圆或多边形内单击

c++ - 模板多态性可以用来代替 OO 多态性吗?

canvas - Raphael js使用canvas还是svg?