我有一个对象文字,如下所示。在Init
方法中,我为单击事件设置了一个处理程序。稍后,当调用处理程序时,我希望使用this
关键字访问this
属性。在这一点上,this
具有jQuery的含义。
另外,为了明确起见,我不希望实现与选择器一致的函数。
var StackOver = {
Bar: "MyBarValue",
Init: function(){
$("#postId").click(this.Foo);
},
Foo: function(eventObject){
// here **this** is jQuery keyword
// how do I access StackOver.Bar?
}
}
如何在Foo
中访问此对象文字的属性
如果我使用构造函数文字,这可能会很容易,这对我来说不是一件容易的事:
var StackOver = function (){
var self = this;
function bar()
{
// I can use self here
}
}
编辑我忘了在这个对象文字中使用显示模块模式,它对对象隐藏私有属性。
发布于 2014-01-09 18:40:08
一种选择:
Init: function(){
$("#postId").click(this.Foo.bind(this));
}
另一种选择:(来自http://api.jquery.com/jquery.proxy/)
Init: function(){
$("#postId").click($.proxy(this.Foo, this));
}
this
和都使用变量,因此不能将this
用于其他目的。
但是,如果不能使用this
**:**,则
Init: function(){
$("#postId").click(function (self) {
return function (event) {
return self.Foo(self, event);
}
}(this));
}
在Foo中,只需添加self
参数。
Foo: function (self, event...) {
...
}
所有这些都说明,为什么不能使用(function () {var self = this; ... }())
呢?毕竟,是的显示模块模式。
发布于 2014-01-09 18:42:02
其他人都建议使用.bind
,这是有意义的,但您也可以在闭包中引用对象本身:
Foo: function(eventObject) {
console.log(StackOver.Bar);
}
发布于 2014-01-09 18:40:47
var StackOver = {
/*...*/
Init: function(){
$("#postId").click(this.Foo.bind(this));
},
/*...*/
Foo: function(eventObject){
// here **this** was actually the html element
// now it's the old this.
alert(this.Bar);
}
}
https://stackoverflow.com/questions/21028414
复制相似问题