2013-04-22 47 views
0

这是我试图执行的示例代码。Javascript嵌套的原型方法范围

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?

+1

我不会推荐定义一个'.call()'方法。尽管它在技术上可能在某些情况下起作用,但它可能会让人们用每个函数已有的Function.call()来混淆。 – jfriend00 2013-04-22 04:45:35

+0

您不应该使用['writeln'](http://www.w3.org/TR/2000/WD-DOM-Level-2-HTML-20001113/html.html#ID-35318390)文档被关闭(例如,在加载事件被调度之后),它将首先调用['document.open'](http://www.w3.org/TR/DOM-Level-2-HTML/html.html# ID-72161170),它将清除现有内容的文档。 – RobG 2013-04-22 05:01:02

回答

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

原型用于定义功能 - 不叫它

+0

啊谢谢!将很快检查你 – 2013-04-22 04:46:15

0

永远,请永不覆盖本地方法(如在这种情况下call)..

也像这个工程太

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

'call'不是对象的本地函数,它存在于'Function.prototype'上,但在这种情况下不会被隐藏。我同意你应该避免命名函数'call',但它不是那么重要。 – zzzzBov 2013-04-22 04:50:36

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' 
0

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

> Game.prototype.say(); 

要调用sayGame.prototype的方法,所以在功能:

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

this是原型对象的引用,而不是实例。你要调用的函数为:

this.say(); 

因此它被称为实例的方法,从而内say设置this的实例。