call、apply、bind 的用法分别是什么?
什么是this
?
要明白上述call、apply、bind
的用法,我们就必须要明白一个更加重要的概念this
关键字
let user = {
name: "John",
age: 30,
sayHi() {
alert(this.name);
}
};
user.sayHi(); // 弹出John
- 请问这个
this
是谁?
- 这个
this
就是指这个函数user
本身,他自己调用了自己 - 在使用
this
中我们要记住一个重要概念 => 谁调用了this,谁就是this这个对象
this
不受限制
let user = { name: "one" };
let admin = { name: "two" };
function sayHi() {
alert( this.name );
}
user.f = sayHi;
admin.f = sayHi;
user.f(); // one
admin.f(); // two
- 如果 obj.f() 被调用了,则 this 在f函数调用期间是obj
- 在上述代码中
user.f()
,this就是user;当admin.f()
调用时,this
就是adminr
- 在上述代码中
现在我们已经知道了,谁调用了this,谁就是this这个对象,那么这个this,是否可指定呢?
call的用法?
- call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数
- call() 接受的是一个参数列表
function sayHi() {
alert(this.name);
}
let user = { name: "one" };
let admin = { name: "two" };
sayHi.call( user ); //指定this为user
sayHi.call( admin ); //指定this为admin
sayHi.call( 1 );
通过上述代码我们可以发现,this是通过call来指定的
apply的用法?
- apply() 方法调用一个具有给定this值的函数,以及作为一个数组(或类似数组对象)提供的参数。
- apply()接受的是一个数组
let user = [1,5,6]
function admin(x){
console.log(this[x])
}
admin.apply(user,[2]) //打印出6
通过上述代码我们可以发现,this是通过apply来指定的,后面传的传参是数组
bind的用法?
- bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
- bind创建一个函数,使这个函数不论怎么调用都有同样的 this 值。
let admin = {
x: 99,
setY: function() { console.log(this.x); }
};
admin.setY(); // 返回 99
let userX = admin.setY();
userX(); //返回 undefined
let userY= userX.bind(admin); // 返回 99
通过上述代码我们可以发现,this是通过bind来绑定,并且用怎么调用都有同样的 this 值