更改函数的目的是什么';javascript中的上下文?
对于这段代码,我已经将函数的“this”上下文更改为数组实例的对象更改函数的目的是什么';javascript中的上下文?,javascript,function,web,this,Javascript,Function,Web,This,对于这段代码,我已经将函数的“this”上下文更改为数组实例的对象 function arrayContext(other_values){ //... console.log(this); //... do something with other_values } arrayContext.call([1],some_other_values) 但这样做的目的是什么?在什么情况下更改函数的上下文是有用的?我认为在.call、.apply和.bind,call可能是使
function arrayContext(other_values){
//...
console.log(this);
//... do something with other_values
}
arrayContext.call([1],some_other_values)
但这样做的目的是什么?在什么情况下更改函数的上下文是有用的?我认为在
.call
、.apply
和.bind
,call可能是使用最少的方法-但这三种方法都用于更改函数的范围
在我看来,.bind
是最有用的,因为它返回一个具有强制作用域的函数,其中.call
和.apply
将立即执行一个函数
以下面的人为例,如果您想在维护对象的范围时使用某些方法作为事件处理程序,那么您应该使用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
通常用于利用某些原型方法,而这些原型方法通常不可用
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);
}
当函数期望
的值为特定值时,此
。jQuery事件处理程序就是一个例子。它们创建一个特定的回调,它模仿本机事件处理程序,在这种情况下,this
被设置为触发它的元素