在javascript中更改函数的上下文的目的是什么?

时间:2013-08-09 15:11:00

标签: javascript function web this

对于这段代码,我已将函数“this”的上下文更改为作为数组实例的对象

function arrayContext(other_values){
    //...
    console.log(this);
    //... do something with other_values
}
arrayContext.call([1],some_other_values)

但这样做的目的是什么?在什么情况下,更改函数的上下文是否有用?

1 个答案:

答案 0 :(得分:2)

我认为.call.apply.bind,调用可能是最少使用的 - 但所有3种方法都用于更改函数的范围。

在我看来.bind是最有用的,因为它返回一个带有强制范围的函数,其中.call.apply将立即执行一个函数。

采用以下设计的示例,如果您想在保持对象范围的同时使用某些方法作为事件处理程序,那么您将使用bind,否则范围将更改为我们将事件绑定到的元素。 / p>

var singleton = {
  prop: 'howdy do!',

  method: function() {
    this.doSomething();
  },

  doSomething: function() {
    console.log(this.prop);
  }
};

$('#thing').on('click',singleton.method.bind(singleton));

.apply最常用于将单个数组转换为参数集合。

var args = ['one', 2, false];

var singleton = {

  setStuff: function(place, index, isSomething) {
    this.place = place;
    this.index = index;
    this.isSomething = isSomething;
  }

};

singleton.setStuff.apply(singleton, args);

.call通常用于利用某些原型方法,而这些方法通常不可用。

function myFunc() {
    // arguments isn't an array, so it doesn't have access to slice
    // however, by scoping the slice method to arguments, we can still use it
    var args = Array.prototype.slice.call(arguments, 0);

    singleton.setStuff.apply(singleton, args);
}