this 引用的是函数执行的环境对象。由于在调用函数之前,this 的值不确定,因此 this 可能会在代码执行过程中引用不同的对象。

设置函数体内的 this 值

下面几种方式,用途都是在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。其强大之处在于能够扩充函数赖以运行的作用域。

apply()

apply() 方法接收两个参数:第一个是在其中运行函数的作用域,另一个是参数数组。第二个参数可以是 Array 的实例,也可以是 arguments 对象。

  1. function sum(num1, num2) {
  2. return num1 + num2
  3. }
  4. function callSum1(num1, num2) {
  5. return sum.apply(this, arguments)
  6. }
  7. function callSum2(num1, num2) {
  8. return sum.apply(this, [num1, num2])
  9. }
  10. console.log(callSum1(10, 10)); // 20
  11. console.log(callSum2(20, 20)); // 20

扩展作用域

  1. const o = {
  2. color: 'blue'
  3. };
  4. function sayColor () {
  5. console.log(this.color);
  6. }
  7. sayColor.apply(o) // 'blue'

call()

call()apply () 作用相同,区别仅在于接收参数的方式不同。

  1. function sum(num1, num2) {
  2. return num1 + num2
  3. }
  4. function callSum(num1, num2) {
  5. return sum.call(this, num1, num2)
  6. }
  7. console.log(callSum(10, 10));
  1. const o = {
  2. color: 'blue'
  3. };
  4. function sayColor () {
  5. console.log(this.color);
  6. }
  7. sayColor.call(o) // blue

bind()

这个方法会创建一个函数的实例,其 this 值会被绑定到传给 bind() 函数的值。

  1. const o = {
  2. color: 'blue'
  3. };
  4. function sayColor () {
  5. console.log(this.color);
  6. }
  7. const objectSayColor = sayColor.bind(o);
  8. objectSayColor(); // blue