如何在IE-8 Javascript的函数体中绑定"this"?

010*_*101 2 javascript internet-explorer-8

我正在做一些跨浏览器测试. 最初,我在ECMAScript 5中使用了bind()关键字.它在IE8中不可用.作为解决方法,我使用Yehuda Katz的一些代码.他的网站建议在不存在绑定时使用实用程序函数代替bind() - 它在IE 8中不存在.

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

   var bind = function (func, thisValue) {
           return function () {
                   return func.apply(thisValue, arguments);
           }
   }
Run Code Online (Sandbox Code Playgroud)

在尝试使用它时,我得到一个异常,它说"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)
           });
Run Code Online (Sandbox Code Playgroud)

已经成为

   $("#Slider").slider({
           slide: bind(this, this.OnSlider_Change),
           change: bind(this, this.OnSlider_Change)
   });
Run Code Online (Sandbox Code Playgroud)

Sam*_*lgh 6

使用jquery,您可以使用实现bind方法正在执行的代理方法.

$("#Slider").slider({
    slide: $.proxy(this.OnSlider_Change, this),
    change: $.proxy(this.OnSlider_Change, this)
});
Run Code Online (Sandbox Code Playgroud)