2014-01-21 2 views
3

안녕하세요 stackoverflow 사람들, 저는 HTML5와 자바 스크립트를 망설이고 있습니다. 함수가 C# 클래스에 추가 된 것처럼 자바 스크립트에서 객체에 함수를 추가하려고합니다. 다음은 지금이 당연히 나를 알 수 있도록자바 스크립트 함수에 객체를 추가하려면

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

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

처럼 내 주요 루프 기능에서 이제

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; 
} 

(I이 작동하지 않습니다 알고) 내 자바 스크립트입니다

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

방법 사용할 수 있도록 함수를 연결하면

hero.MoveHero(x,y); 

누군가 나를 도울 수 있다면 정말 좋을 것입니다.

P. 내 영웅 변수를 전 세계적으로 선언하고 있습니다.

var hero = new Hero(); 

괜찮습니까?

+0

'Hero.prototype.MoveHero = 기능 (...) 나는 :) 환호 찾고 있던 하나 인' –

답변

10

가능합니다.

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

네. – Canvas

1
function Hero() 
{ 
    // add other properties 

    this.MoveHero = function(xSpeed, ySpeed) 
    { 
     this.xPos += xSpeed; 
     this.yPos += ySpeed; 
    } 
} 
관련 문제