javascript - 是否有更标准的方法来处理 "this"而不使 "that"引用 "this"

标签 javascript jquery

我这里有一些代码:

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/

相关文章:

Javascript - 停止幻灯片超时

javascript - 替代循环中的 'let' 关键字?

javascript - JQuery,表格单元格上的事件冒泡。如何计算出点击了哪一行

javascript - Bootstrap Datepicker定位不起作用

php - 跨域GET JSON编码字符串?

javascript - 添加 jQuery 验证方法时 this.optional(element) 做了什么?

javascript - 使用 jquery 从上到下淡化和翻译 "position:absolute"元素

javascript - 与 DIV 的水平滚动条作斗争

javascript - 如何在翻书前后居中翻书

javascript - 压缩 Highcharts 中的 x 轴