范围$ .each函数(绑定)

时间:2013-11-25 20:57:20

标签: jquery scope bind

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

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

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

我如何在JQuery中执行此操作?

2 个答案:

答案 0 :(得分:2)

bind是vanilla JS。

jQuery为没有bind的非常旧的浏览器提供proxy功能(即I.E. 8 - )

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

你的$.proxy循环,也在使用IE8:

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

答案 1 :(得分:0)

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;
                };
            }