【发布时间】:2010-07-20 21:14:55
【问题描述】:
我是基于原型的语言的新手,并且已经阅读了这个问题:
Preserving a reference to "this" in JavaScript prototype functions
我想知道使用基于原型的签名将方法附加到对象有什么价值。为什么不直接将方法附加到对象定义中的对象属性上?
其次,当使用原型签名定义对象的方法时,为什么'this'指针会解析到函数内部的窗口对象?这似乎是一个设计缺陷。如果不是,有人可以解释一下,或者指出我为什么不解释吗?
谢谢。
编辑:
此代码按预期执行,呈现一个消息框,其中包含单词“here”。
function Obj() {
this.theVar = 'here';
this.method2 = function(){ alert( this.theVar ); }
}
Obj.prototype.method3 = function(){ this.method2(); }
Obj.prototype.method4 = function(){ this.method3(); }
var obj = new Obj();
obj.method4();
这段代码是我的AJAX回调,执行过程中'this'指针指向'window'对象。
Test.prototype.nextCallback = function( response ) {
if( response.Status != 'SUCCESS' )
show_message( response.Message, false );
else
this.setQuestion( response.Question );
}
Test.prototype.setQuestion = function( question ){ ... }
'this' 指针实际上在 AJAX 调用之前可以正常工作,但不能在之后。这是因为在 AJAX 调用返回之后和调用回调之前没有正确恢复 nextCallback() 上下文吗?有没有办法解决这个问题?
【问题讨论】:
-
我不认为你的意思是“原型签名”——你说的是原型属性,不是吗?
-
“原型签名”是指定义这样的方法:myObj.prototype.myFunction = function(){ ... }
标签: javascript prototype bind