每个函数都包含两个非继承而来的方法:call()和apply();
在JavaScript中,call和apply作用是一样的,都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向。
bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。
apply/call/bind可以动态改变this指向
var o = {name:'abc'};
function f() {
console.log(this.name);
}
f();//undefined
f.apply(o);//abc
f.call(o);//abc
f.bind(o)();//abc(bind 返回的是一个新的函数,你必须调用它才会被执行。)
//f()=f.apply()=f.call()
区别:参数书写方式不同
call(thisObj, arg1, arg2, arg3);
apply(thisObj, [args]);
bind(this.Obj,arg1, arg2, arg3)();
- apply
function f(s) {
console.log(this.a, s);
return this.a + s;
}
var obj = {
a: 2
}
var f2 = function () {
return f.apply(obj, arguments);//arguments==[3]
}
var b = f2(3);
console.log(b);
//2 3 5
//扩展
var arr = [1,21,33,4,66]
var max = Math.max.apply(Math,arr)
console.log(max)//66
- call
function f(s) {
console.log(this.a, s);
return this.a + s;
}
var obj = {
a: 2
}
var f2 = function () {
return f.call(obj, ...arguments);//...arguments==3
}
var b = f2(3);
console.log(b);
//2 3 5
- bind
function f(s) {
console.log(this.a, s);
return this.a + s;
}
var obj = {
a: 2
}
var f2 = function () {
return f.bind(obj, ...arguments)();//传参与call一样,只是多了()调用
}
var b = f2(3);
console.log(b);
//2 3 5
//扩展发送短信验证
btn.onclick = function(){
this.disabled = true
setTimeout(function(){//默认this = window
this.disabled = false//this = btn
}.bind(this),60000)//把this改成btn,并60s后调用,不要加()
}