是否有一些更标准的处理"this"而没有对"this"进行"那个"引用

Ale*_*euk 2 javascript jquery

我这里有一些代码:

App.prototype.binds = function(){
    var that = this;
    $('.postlist li').live('click', function(){ that.selectPost(this);} );
}

App.prototype.selectPost = function(){
    this.function();
}
Run Code Online (Sandbox Code Playgroud)

我在我的binds函数中创建了"this"的引用,因此在我的selectPost()中,我可以使用"this"来引用App对象而不是列表项.

是否有更优雅/标准的解决方案,而不是使用"那"?


通过答案,我的代码变为:

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); 
}
Run Code Online (Sandbox Code Playgroud)

Esa*_*ija 5

您可以在构造函数中或正好绑定函数:

在构造函数中

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
}
Run Code Online (Sandbox Code Playgroud)

及时:

App.prototype.binds = function(){
    $('.postlist li').live('click', this.selectPost.bind( this ));
                                    //$.proxy( this.selectPost, this ) in jQuery
}
Run Code Online (Sandbox Code Playgroud)

请注意,.bind仅在较新的浏览器中支持,jQuery $.proxy应该首选.

我已经在jQuery中打开了一个已被接受的功能请求http://bugs.jquery.com/ticket/12031.使用jQuery事件时,这将使这更容易.

请注意,在jQuery事件处理程序中,存在一个常见的误解,即e.target它与正常情况相同this.实际上e.currentTarget.所以现在this指的是实例而不是元素,你可以通过它来获得elemet e.currentTarget.