2012-02-13 27 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

相关问题