Paweł Kwiatkowski
Paweł Kwiatkowski

Reputation: 79

JS OOP outside prototype function call ( scope )

I'm new to OOP, and I'm writing a simple game script to learn the OOP principles.

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

I want to access enterMonsterMenu() method by calling the monsterSelectUp() but I can't call it properly. What I am doing wrong ?

Upvotes: 3

Views: 1252

Answers (1)

Borys Serebrov
Borys Serebrov

Reputation: 16182

It looks like you didn't get the concepts right, try to re-read at least this short intro.

Let's try to look what happens in the line where you are trying to call "enterMonsterMenu". Here it is:

battleLevel.prototype.battle.call(obj1);

The battleLevel.prototype is an object you defined first. The battleLevel.prototype.battle is a function and you execute it's "call" method (because functions are also objects in js and have functions like "call").

What does "function.call" method? It calls the function with given this value. For example,

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

In your code, you are trying to call the battleLevel.prototype.battle and passing the obj1 as this.

But at that point of code there is no obj1 variable defined, so you just call the battle method with undefined variable.

Moreover, even if you passed the defined variable, you would not call the enterMonsterMenu function anyway. Because your method only adds the obj1 property to the this object:

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();

You can see above how you can actually call your enterMonsterMenu, but to be honest, I see no point in doing things like this. And, as I said, you probably need to spend more time on learning the concepts.

Upvotes: 1

Related Questions