【问题标题】:scoping $.each function (binding)作用域 $.each 函数(绑定)
【发布时间】:2013-11-25 20:57:19
【问题描述】:

我习惯了 Mootools,它有一个绑定方法。 据我所知,JQuery 的 bind() 用于事件。

所以,在类方法中,我习惯这样做:

$.each(items,function(index,item){
 //[...] then here this refers to the class constructor, not item
}.bind(this));

如何在 JQuery 中做到这一点?

【问题讨论】:

  • 你知道bind是香草JS吗?
  • 是的,但它只支持 IE9+,直到 IE11,我仍然(遗憾)支持 IE8

标签: jquery scope bind


【解决方案1】:

bind 是原版 JS。

jQuery 为没有bind 的非常旧的浏览器提供了proxy 函数(即IE 8-)

请注意,具有bind 功能的浏览器也具有Array.prototype.forEach 功能,这使得$.each 通常无用。

$.proxy 的循环也适用于 IE8:

$.each(items, $.proxy(function(index,item){
      // here, this is the outside this
}, this));

【讨论】:

  • 谢谢,我知道,但我现在还需要IE8。
  • @Stratboy 我可能不清楚,我编辑以展示如何使用 $.proxy。
  • 是的,这也是我的问题的解决方案!谢谢你:)
【解决方案2】:

IE8 的答案来自这里:

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

// Credit to Douglas Crockford for this bind method
            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;
                };
            }

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多