我这里有一些代码:
App.prototype.binds = function(){
var that = this;
$('.postlist li').live('click', function(){ that.selectPost(this);} );
}
App.prototype.selectPost = function(){
this.function();
}
我在绑定(bind)函数中创建了“this”的引用作为“that”,因此在 selectPost() 中,我可以使用“this”来引用 App 对象而不是列表项。
是否有更优雅/标准的解决方案来代替使用“that”?
有了答案,我的代码就变成了:
App.prototype.binds = function(){
$('.postlist li').live('click', $.proxy(this.selectPost, this) );
}
App.prototype.selectPost = function(e){
this.function(); // function in App
var itemClicked = e.currentTarget; //or
var $itemClicked = $(e.currentTarget);
}
最佳答案
您可以在构造函数中绑定(bind)函数,也可以及时绑定(bind)函数:
在构造函数中
function App() {
this.selectPost = this.selectPost.bind( this );
//$.proxy( this.selectPost, this ) in jQuery
}
App.prototype.binds = function(){
$('.postlist li').live('click', this.selectPost ); //Already bound in constructor
}
及时:
App.prototype.binds = function(){
$('.postlist li').live('click', this.selectPost.bind( this ));
//$.proxy( this.selectPost, this ) in jQuery
}
请注意.bind
仅在较新的浏览器中受支持,jQuery 有 $.proxy
这应该是首选。
我已经在 jQuery 中打开了一个功能请求,该请求已被接受 http://bugs.jquery.com/ticket/12031 。使用 jQuery 事件会使这变得更容易。
请注意,有一个常见的误解:e.target
与 jQuery 事件处理程序中的普通 this
相同。它实际上是e.currentTarget
。所以现在 this
引用的是实例而不是元素,您可以通过 e.currentTarget
获取 elemet。
关于javascript - 是否有更标准的方法来处理 "this"而不使 "that"引用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452713/