Rumah > Soal Jawab > teks badan
大家好,我自己正在研究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
天蓬老师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;
}
}