JavaScript 单例方法上的 _.bindAll() ?
下面代码中的方法 obj2.method1 是从另一个对象调用的。 如何绑定“this context”以便我可以从 obj2 引用 obj1?
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
}
}
我尝试使用下划线 _.bindAll() - 类似的东西 - 但失败了......
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
},
init : function(){
_.bind(this, obj2.method1)
}
}
singleton.init();
谢谢:)
The method obj2.method1, in the code below, is called from another object.
How do I bind the "this context" so that I can refer to obj1 from obj2?
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
}
}
I tried using underscore _.bindAll() - something along these lines - but failed ...
var singleton = {
obj1 : {
a : 5
},
obj2 : {
method1 : function(){
this.obj1.a; //undefined
}
},
init : function(){
_.bind(this, obj2.method1)
}
}
singleton.init();
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用
_.bind()
的结果重新分配singleton.obj2.method2()
:// 在 .init() 中:
this.obj2.method1 = _.bind(this.obj2.method1, this)
To
singleton.init()
在调用时有一个正确的this
,您需要显式指定它:singleton.init.call(singleton)
完整演示此处。但请记住,
Singleton
模式是 < a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/" rel="nofollow">不好,我可以吗?You need to reassign
singleton.obj2.method2()
with the results of_.bind()
:// in .init():
this.obj2.method1 = _.bind(this.obj2.method1, this)
To have
singleton.init()
have a properthis
when called, you need to specify it explicitly:singleton.init.call(singleton)
Full demonstration here. But remember, the
Singleton
pattern is bad, m'kay?