찾다

 >  Q&A  >  본문

html5 - 如何在JavaScript对象中添加函数?

大家好,我自己正在研究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中文网2895일 전488

모든 응답(1)나는 대답할 것이다

  • 天蓬老师

    天蓬老师2017-04-10 13:13:09

    解决方案
    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
  • 취소회신하다