2012-02-13 55 views
2

我正在做一些跨瀏覽器測試。 Initially, I was using the bind() keyword in ECMAScript 5。它在IE8中不可用。作爲解決方法,我使用了來自Yehuda Katz的一些代碼。他的網站提出替代的bind()的使用效用函數時綁定不存在 - 它不會在IE 8如何在IE-8 Javascript的函數體中綁定「this」?

http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

var bind = function (func, thisValue) { 
      return function() { 
        return func.apply(thisValue, arguments); 
      } 
    } 

存在在嘗試使用它,我當它說「func.apply」時會得到一個異常。我沒有傳入一個函數,我傳遞了一個對象,所以apply()不在那裏。精細。但是現在我又被卡住了,回到方塊1.我如何將「this」變量綁定到函數體?

摘要:如何將「this」變量綁定到函數體?

<snip> 

    MyView.prototype.OnSlider_Change = function (event, ui) { 
      this.viewModel.setVariableX(ui.value * 100.0); 
    } 

<snip> 

    $("#Slider").slider({ 
        slide: (this.OnSlider_Change).bind(this), 
        change: (this.OnSlider_Change).bind(this) 
      }); 

已成爲

$("#Slider").slider({ 
      slide: bind(this, this.OnSlider_Change), 
      change: bind(this, this.OnSlider_Change) 
    }); 
+2

Yehuda Katz不是JavaScript的發明者;)他是個很酷的人,他非常熟悉JavaScript。 – yatskevich 2012-02-13 17:36:55

回答

2

你剛剛得到了參數順序錯誤對於墊片:

 slide: bind(this.OnSlider_Change, this), 
     change: bind(this.OnSlider_Change, this) 
6

與jQuery你可以用它實現你的綁定方法是做proxy method

$("#Slider").slider({ 
    slide: $.proxy(this.OnSlider_Change, this), 
    change: $.proxy(this.OnSlider_Change, this) 
}); 
+1

太棒了!兩個很好的答案! – 010110110101 2012-02-13 20:44:17

相關問題