Javascript嵌套原型方法作用域

Javascript nested prototype method scope

本文关键字:作用域 方法 原型 嵌套 Javascript      更新时间:2023-09-26

下面是我要执行的示例代码。

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

结果是yeah undefined,这意味着call()工作正常,而say()不是。我怎么做才能得到say()函数。状态从游戏对象?

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

prototype用于定义函数而不是调用它

千万不要重写本地方法(比如本例中的call).

也可以这样

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

看起来你想要的是:

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

但是这个版本将调用在this.say设置的任何函数,如果对象被继承,该函数可能被覆盖:

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

如果您想使用对Game.prototype.say的原始引用(没有继承),那么您需要在对象的上下文中调用该函数:

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

TGH给了你一个解决方案,但没有解释。你的问题在这里:

> Game.prototype.say();

您正在调用say作为Game.prototype的方法,因此在函数中:

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

this是对原型对象的引用,而不是实例。您希望以如下方式调用该函数:

 this.say();

使其作为实例的方法调用,从而将say中的this设置为实例