首页 > 解决方案 > 常规函数与箭头函数中的“this”范围

问题描述

myRegFunc指的是this局部范围仅限于users对象。但是,myArrowFunc改为this使用全局范围。有没有办法this在箭头函数中引用与常规函数相同的信息?

那么箭头函数不能绑定到本地this?但是,是否仍然可以通过全局 this 获取本地 this 信息?例如:全局 this.something.something ... = 本地 this。

const users = {
  name: 'John',
  myRegFunc: function() {
    console.log('myRegFunc : ', this);
  },
  myArrowFunc: () => console.log('myArrowFunc this: ', this),
};
users.myRegFunc();
users.myArrowFunc();

输出:

myRegFunc :  {name: 'John', myRegFunc: ƒ, myArrowFunc: ƒ}
arrowFunc.js:34 myArrowFunc this:  Window {window: Window, self: Window, document: document, name: '', location: Location, …}

标签: javascriptarrow-functions

解决方案


推荐阅读