Henry Cho
Henry Cho

Reputation: 770

Javascript nested prototype method scope

Here is the sample code that I am trying to execute.

var Game = function(){
  this.state = 'yeah';
}

Game.prototype.call = function(){
  document.writeln(this.state);
  Game.prototype.say();
}

Game.prototype.say = function(){
  document.writeln(this.state);
}

game = new Game();
game.call();

The result is yeah undefined which means that the call() is working properly while the say() isn't. What can I do for say() function to be able to get this.state from Game object?

Upvotes: 0

Views: 831

Answers (4)

RobG
RobG

Reputation: 147413

TGH has given you a solution but not explained it. Your problem is here:

> Game.prototype.say();

You are calling say as a method of Game.prototype, so in the function:

> Game.prototype.say = function(){
>   document.writeln(this.state); 
> }

this is a reference to the prototype object, not the instance. You want to call the function as:

 this.say();

so that it's called as a method of the instance, thereby setting this within say to the instance.

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179136

It looks like what you want is:

Game.prototype.call = function(){
  document.writeln(this.state);
  this.say();
}

However this version will call whatever function is set at this.say, which might be overridden if the object is inherited:

var MyGame = function () {};
MyGame.prototype = new Game();
MyGame.prototype.say = function () {
    document.writeln('something else');
};
var m = new MyGame();
m.call(); //'something else'

If you want to use the original reference to Game.prototype.say (without inheritance), then you'll need to call the function in the context of the object:

Game.prototype.call = function(){
  document.writeln(this.state);
  Game.prototype.say.call(this);
}
var m = new MyGame();
m.call(); //'yeah'

Upvotes: 0

Orlando
Orlando

Reputation: 9702

never, please never override native methods (like call in this case)..

also something like this works too

Game.prototype.call = function(){
  document.writeln(this.state);
  Game.prototype.say.apply(this);
}

Upvotes: 0

TGH
TGH

Reputation: 39268

Game.prototype.call = function(){
  document.writeln(this.state);
  this.say();
}

prototype is used in for defining the function - not calling it

Upvotes: 2

Related Questions