对于这个代码块,我已经将函数的“this”的上下文更改为一个对象,该对象是数组的一个实例
function arrayContext(other_values){
//...
console.log(this);
//... do something with other_values
}
arrayContext.call([1],some_other_values)
但是这样做的目的是什么?在什么情况下更改函数的上下文会有用?
最佳答案
我认为在 .call
、.apply
和 .bind
中,call 可能是用得最少的——但是这 3 种方法都用到了更改函数的范围。
在我看来 .bind
是最有用的,因为它返回一个带有强制作用域的函数,其中 .call
和 .apply
将立即执行一个函数。
举下面这个人为的例子,如果你想在维护对象范围的同时使用某些方法作为事件处理程序,那么你应该使用绑定(bind),否则范围将更改为我们将事件绑定(bind)到的元素。
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
通常用于利用某些通常不可用的原型(prototype)方法。
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);
}
关于javascript - 在javascript中更改函数上下文的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18149980/