2016-06-13 2 views
3

OOP를 처음 접했고 OOP 원칙을 배우기 위해 간단한 게임 스크립트를 작성하고 있습니다.프로토 타입 함수 호출 (범위) 외부의 JS OOP

//main game function 
battleLevel.prototype = 
{ 

    battle:function() {  
     this.obj1 = { 
      enterMonsterMenu: function() { 
      return console.log('enterMonsterMenu'); 
      } 
     };  
    },  

} /* end OOP prototype */ 



//external contructor 
var Hero = function (warpX, warpY, game, name, life, mana, speed) { 
    //some code 
}; 

Hero.prototype.monsterSelectUp = function() { 
    console.log('monsterSelectUp'); 
    //this.enterMonsterMenu(); 
    battleLevel.prototype.battle.call(obj1); 
}; 

은 내가 monsterSelectUp()를 호출하여 enterMonsterMenu() 메소드에 액세스하려면하지만 난 그것을 제대로 호출 할 수 없습니다. 내가 뭘 잘못하고 있니?

답변

1

개념을 제대로 이해하지 못한 것 같습니다. 최소한 this short intro을 다시 읽으십시오.

"enterMonsterMenu"라고하는 행에서 어떤 일이 일어나는지 보도록하겠습니다. 는 여기있다 :

battleLevel.prototype.battle.call(obj1); 

battleLevel.prototype은 먼저 정의 된 개체입니다. battleLevel.prototype.battle은 함수이며 "호출"메소드를 실행합니다 (함수는 js의 객체이기도하고 "호출"과 같은 기능을 갖기 때문입니다).

"function.call"은 무엇입니까 method? 주어진 this 값으로 함수를 호출합니다. 예를 들어 ,

var myObject = { name: "Object 1" }; 
 
var yourObject = { name: "Object 2" }; 
 

 
function test() { 
 
    alert(this.name); 
 
} 
 

 
test.call(myObject); //alert Object 1 
 
test.call(yourObject); //alert Object 2
코드에서

, 당신은 battleLevel.prototype.battle 전화를 시도하고 obj1 this로 전달된다.

그러나이 코드 지점에는 obj1 변수가 정의되어 있지 않으므로 battle 메서드를 정의되지 않은 변수와 함께 호출하면됩니다.

또한 정의 된 변수를 전달한 경우에도 enterMonsterMenu 함수를 호출하지 않아도됩니다. 당신의 방법은 오직 this 객체에 obj1 속성을 추가하기 때문에 :

battleLevel = {} 
 
battleLevel.prototype = 
 
{ 
 

 
    battle:function() {  
 
     this.obj1 = { 
 
      enterMonsterMenu: function() { 
 
      alert('enterMonsterMenu'); 
 
      } 
 
     };  
 
    },  
 

 
} 
 

 

 
var myThis = {"property": "value"}; 
 
alert(JSON.stringify(myThis)); // {"property": "value"}; 
 
// This call will add "obj1" property to myThis 
 
battleLevel.prototype.battle.call(myThis); 
 
alert(JSON.stringify(myThis)); // {"property": "value", "obj1": {}}; 
 
// now call the 'enterMonsterMenu' 
 
myThis.obj1.enterMonsterMenu();

당신은 실제로 당신의 enterMonsterMenu를 호출하는 방법을 위에 볼 수 있지만 솔직히 말해서, 나는이 일을 아무 문제를 볼 수 없습니다 이렇게. 그리고 제가 말씀 드렸듯이 개념을 익히는 데 더 많은 시간을 할애해야 할 것입니다.

+0

답장을 보내 주셔서 감사합니다. :) 여기 범위 문제를 해결하려고합니다. battleLevel.prototype 내부에있는 다른 메서드를 다른 프로토 타입 메서드에서 호출 할 수 있는지조차 모르겠습니까? –

+1

@ PawełKwiatkowski 당신은 프로토 타입에서 메소드를 호출해서는 안됩니다. 대신에 일반 오브젝트를 작성하여 사용해야합니다. 예를 들어,'level = new BattleLevel(); 영웅 = 새로운 영웅(); hero.enterLevel (레벨)'과'enterLevel' 안에 레벨 메소드'level.doSomethingWithHero (this)'를 호출 할 수 있습니다. –

+0

@ PawełKwiatkowski 또한 '전투'방법에서 새 오브젝트를 생성하고 'this'에 지정하는 것이 중요하지 않습니다. 무엇을 성취하려고합니까? "obj1"의 목적은 무엇입니까? –