搜索
html5 - 如何在JavaScript对象中添加函数?
PHP中文网
PHP中文网 2017-04-10 13:11:09
[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中文网

认证0级讲师

全部回复(1)
天蓬老师

解决方案
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;
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号