html5 - 如何在JavaScript对象中添加函数?
PHP中文网
PHP中文网 2017-04-10 13:11:09
0
1
496

大家好,我自己正在研究HTML5和JavaScript,我尝试在JavaScript中添加一个函数到对象中,就好比在C#中把一个函数添加到类中。下面是我的JavaScript代码,但却不能正常运行。

function Hero()
{
    this.xPos = 100;
    this.yPos = 100;
    this.image = new Image();
    this.image.src = "Images/Hero.png";
}

function MoveHero( xSpeed, ySpeed )
{
    xPos += xSpeed;
    yPos += ySpeed;
}

主循环函数如下:

function main()
{
    canvas.fillStyle = "#555555";
    canvas.fillRect( 0, 0, 500, 500);

    canvas.drawImage( hero.image, hero.xPos, hero.yPos );
    hero.MoveHero(1,1);
}

运行后去提示:.

"Uncaught TypeError: Object #<Hero> has no method 'MoveHero'"

我应该如何连接下面函数?

hero.MoveHero(x,y);

PS. hero是全局变量,这样可以吗?

var hero = new Hero();

原问题:Javascript add function to object

PHP中文网
PHP中文网

认证0级讲师

全員に返信(1)
Peter_Zhu

解决方案
Alex K. :你可以这样做。

Hero.prototype.MoveHero = function( xSpeed, ySpeed )
{
    this.xPos += xSpeed;
    this.yPos += ySpeed;
}

Rami Enbashi:你尝试下这种方法。

function Hero()
{
    // add other properties

    this.MoveHero = function( xSpeed, ySpeed )
    {
        this.xPos += xSpeed;
        this.yPos += ySpeed;
    }
}
いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート