this 引用的是函数执行的环境对象。由于在调用函数之前,this 的值不确定,因此 this 可能会在代码执行过程中引用不同的对象。
设置函数体内的 this 值
下面几种方式,用途都是在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。其强大之处在于能够扩充函数赖以运行的作用域。
apply()
apply()
方法接收两个参数:第一个是在其中运行函数的作用域,另一个是参数数组。第二个参数可以是 Array 的实例,也可以是 arguments 对象。
function sum(num1, num2) {
return num1 + num2
}
function callSum1(num1, num2) {
return sum.apply(this, arguments)
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2])
}
console.log(callSum1(10, 10)); // 20
console.log(callSum2(20, 20)); // 20
扩展作用域
const o = {
color: 'blue'
};
function sayColor () {
console.log(this.color);
}
sayColor.apply(o) // 'blue'
call()
call()
与 apply ()
作用相同,区别仅在于接收参数的方式不同。
function sum(num1, num2) {
return num1 + num2
}
function callSum(num1, num2) {
return sum.call(this, num1, num2)
}
console.log(callSum(10, 10));
const o = {
color: 'blue'
};
function sayColor () {
console.log(this.color);
}
sayColor.call(o) // blue
bind()
这个方法会创建一个函数的实例,其 this 值会被绑定到传给 bind()
函数的值。
const o = {
color: 'blue'
};
function sayColor () {
console.log(this.color);
}
const objectSayColor = sayColor.bind(o);
objectSayColor(); // blue