2013-11-25 3 views
-1

Я был использован для Mootools, который имеет метод привязки. Связывание JQuery() используется для событий, насколько я могу судить.

Таким образом, в методе класса, я привык делать это:

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

Как я могу сделать это в JQuery?

+1

Вы знаете, 'bind' ваниль JS? –

+0

Именно это !!! – Krishna

+0

Да, но он поддерживается только IE9 +, и до IE11 я все еще (к сожалению) поддерживаю IE8 – Stratboy

ответ

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

Почему бы не использовать '$ .proxy', как я показал вам? –

2

bind is vanilla JS.

JQuery обеспечивает функцию proxy для очень старых браузеров, не имеющие bind (т.е. И.Е. 8-)

Обратите внимание, что браузеры, имеющей функцию bind также имеет Array.prototype.forEach один, что делает $.each чаще всего бесполезно.

Ваш цикл с $.proxy, также работает на IE8:

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

Спасибо, я знал, но мне также нужен IE8. – Stratboy

+0

@Stratboy Я, возможно, был неясен, я отредактировал, чтобы показать, как использовать $ .proxy. –

+0

Да, это тоже решение для моей проблемы! Спасибо :) – Stratboy