返回

箭头函数运用与this指向剖析

前端

es6箭头函数的运用方式

箭头函数是es6中引入的新特性,它以=>取代function,使得代码更加简洁。箭头函数没有自己的this,因此this的指向取决于函数的上下文。箭头函数还有很多其他的特性,比如没有arguments对象,不能用作构造函数,不能使用yield命令等。

箭头函数的this指向

箭头函数的this指向是由其所在的词法作用域决定的。在词法作用域中,this指向最近的非箭头函数作用域。如果一个箭头函数没有在非箭头函数作用域中定义,那么它的this指向全局对象。

实例剖析箭头函数中的this指向

下面的代码演示了箭头函数中的this指向问题:

const person = {
  name: '张三',
  sayHello: () => {
    console.log(this.name);
  }
};

person.sayHello(); // undefined

在这个例子中,箭头函数sayHello没有自己的this关键字,因此this的指向取决于函数的上下文。sayHello函数是在person对象中定义的,因此它的this指向person对象。但是,箭头函数sayHello没有自己的this关键字,因此this的指向取决于函数的上下文。sayHello函数是在全局作用域中调用的,因此它的this指向全局对象。

箭头函数this指向问题的解决方法

箭头函数的this指向问题可以通过以下几种方法来解决:

  1. 使用bind方法。bind方法可以将一个函数的this指向绑定到另一个对象上。下面的代码演示了如何使用bind方法来解决箭头函数this指向问题:
const person = {
  name: '张三',
  sayHello: () => {
    console.log(this.name);
  }
};

const sayHelloBound = person.sayHello.bind(person);
sayHelloBound(); // 张三
  1. 使用箭头函数的call或apply方法。call和apply方法都可以将一个函数的this指向绑定到另一个对象上。下面的代码演示了如何使用call方法来解决箭头函数this指向问题:
const person = {
  name: '张三',
  sayHello: () => {
    console.log(this.name);
  }
};

person.sayHello.call(person); // 张三
  1. 将箭头函数作为非箭头函数的子函数。如果一个箭头函数作为非箭头函数的子函数,那么它的this指向由非箭头函数决定。下面的代码演示了如何将箭头函数作为非箭头函数的子函数来解决this指向问题:
const person = {
  name: '张三',
  sayHello: function() {
    const sayHelloArrow = () => {
      console.log(this.name);
    };

    sayHelloArrow(); // 张三
  }
};

person.sayHello();

结语

箭头函数是es6中引入的新特性,它以=>取代function,使得代码更加简洁。箭头函数没有自己的this关键字,因此this的指向取决于函数的上下文。箭头函数的this指向问题可以通过bind方法、call或apply方法、将箭头函数作为非箭头函数的子函数等方法来解决。