0

这是我尝试执行的示例代码。

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 对象中获取 this.state?

4

4 回答 4

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

原型用于定义函数 - 不调用它

于 2013-04-22T04:45:12.747 回答
0

永远,请永远不要覆盖本机方法(就像call在这种情况下)..

像这样的东西也可以

Game.prototype.call = function(){
  document.writeln(this.state);
  Game.prototype.say.apply(this);
}
于 2013-04-22T04:48:34.370 回答
0

看起来你想要的是:

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'
于 2013-04-22T04:55:01.237 回答
0

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

> Game.prototype.say();

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

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

this是对原型对象的引用,而不是实例。您想将该函数称为:

 this.say();

以便将其作为实例的方法调用,从而设置thissay实例中。

于 2013-04-22T05:07:07.170 回答