javascript - 如果从存储变量调用 jquery 函数,则此绑定(bind)不正确

标签 javascript jquery closures this

我以两种方式调用 jQuery 函数,一种有效,另一种无效,因为 this 绑定(bind)不正确。

$('#my-div').fadeOut();

按预期工作,fadeOut 函数内的 this 的值是 jQuery 对象。

var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn();

不起作用,因为this的值现在是Window

这是包含两个示例的 jsfiddle。

http://jsfiddle.net/XCAdP/

编辑:添加一些关于我发布该问题的原因的说明,我真的不想知道如何解决此问题。这不是问题。我想了解为什么会发生这种情况。

最佳答案

是的,它不知道要应用fadeOut动画的元素,并且在这种情况下,this上下文主要是窗口而不是jquery对象。您可以使用 function.call

传递上下文

试试这个:

var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn.call($('#my-div'));

或者只是这样做:

使用 function.bind 将上下文绑定(bind)到函数引用,并调用它。

var fadeOutFn = $().fadeOut.bind($('#my-div'));
fadeOutFn();

阅读function.bind

对于不支持的浏览器,您可以将其添加到 js 文件中以获取文档中提到的支持:

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

关于javascript - 如果从存储变量调用 jquery 函数,则此绑定(bind)不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328967/

相关文章:

javascript - 如何将变量按值传递给匿名 JavaScript 函数?

swift - 为什么闭包不能关闭实例成员

javascript - 更新时缺少模板 Rails

javascript - 获取可编辑div中选中元素的id

javascript - 在 JavaScript 中格式化整数的最快方法?

jquery - 关于使用 masonry.js 加载图像

javascript - 无限滚动(mysql、php 和 js)循环问题

javascript - 第一次单击时不会开始滚动列表元素

javascript - 如何使这个 javascript 文本效果起作用?

ios - 用户位置更新后触发的函数