简体   繁体   中英

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?

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

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

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

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM