箭头函数和普通函数都可以在 Generator 中使用。在 Generator 中使用函数时,箭头函数和普通函数的主要区别在于 'this' 的指向。箭头函数的 'this' 指向定义时所在的作用域,而普通函数的 'this' 指向调用它的对象。因此,在 Generator 中使用箭头函数可以避免 'this' 指向错误的问题。

例如:

function* generator() {
  yield () => console.log(this); // 箭头函数的 this 指向定义时所在的作用域
  yield function() {console.log(this);} // 普通函数的 this 指向调用它的对象
}

const obj = {name: 'obj'};
const gen = generator.bind(obj);

for(let fn of gen()) {
  fn();
}
// 输出:
// globalThis
// {name: 'obj'}

在上面的例子中,箭头函数的 'this' 指向全局作用域,而普通函数的 'this' 指向调用它的对象(即 obj)。如果没有使用箭头函数,普通函数的 'this' 指向可能会出现错误。

Generator 中箭头函数和普通函数的 this 指向差异

原文地址: https://www.cveoy.top/t/topic/mseb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录