javascript绑定对象的原型函数
如何将对象原型中的 this 指针绑定到对象的实例?
function Foo(){ }
Foo.prototype.f1 = function(){this.f2();} //is wrong because 'this' does not refer to Foo instance
Foo.prototype.f2 = function(){}
这真的很烦人。有人可以帮忙吗?我尝试在 Foo 的构造函数中执行 _.bindAll(this,'f1','f2') 但没有运气。
How would I bind the this pointer in the objects prototype to the object's instance?
function Foo(){ }
Foo.prototype.f1 = function(){this.f2();} //is wrong because 'this' does not refer to Foo instance
Foo.prototype.f2 = function(){}
This is really annoying. Can anyone help? I tried doing _.bindAll(this,'f1','f2') inside Foo's constructor but no luck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您在评论中提到您将
f1
设置为事件处理程序:相反,您可以传递闭包:
或使用 Underscore.js 库的
bind
方法:You mention in a comment that you are setting
f1
as event handler with:Instead, you can pass a closure:
or use the
bind
methods of the Underscore.js library:如果您使用
var foo = new Foo();
,您的代码将正常工作。然后,只需使用 foo.f1(); 即可。 foo 将是f1
中的this
。原因是,当您对构造函数使用
new
时,_proto
链接将附加到将成为新实例的对象。此_proto_
链接指向构造函数的原型。在运行时,如果实例所访问的属性/方法不直接存在于实例上,解释器将遵循_proto_
,并尝试访问那里的属性/方法。如果您想调用带有显式对象作为
this
的函数,可以执行myFunc.call(myObjThatWillBeThis)
。Your code would work correctly if you used
var foo = new Foo();
. Then, just usefoo.f1();
. foo will bethis
inf1
.The reason is that when you use
new
against a constructor function, a_proto
link will be attached to the object that will be the new instance. This_proto_
link points to the prototype of the constructor function. At runtime, if an accessed property/method of the instance does not exist on the instance directly, the interpreter will follow the_proto_
, and try to access the property/method there.If you want to call a function with an explicit object as
this
, you can domyFunc.call(myObjThatWillBeThis)
.您的代码应更改为:
Your code should be changed to:
试试这个:
或者更通用的东西:
Try this:
Or something more generic:
这有效:
http://jsfiddle.net/VYdNx/3/
这样做:
http://jsfiddle.net/VYdNx/2/
This works:
http://jsfiddle.net/VYdNx/3/
As does this:
http://jsfiddle.net/VYdNx/2/