javascript - 常规函数与箭头函数中的“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, …}
解决方案
推荐阅读
- css - React w Gatsby:为什么我的字体文件有时会下载两次
- ios - pattern.firstMatch 得到错误:表达式类型“@lvalue 字符串?” 没有更多上下文是模棱两可的
- javascript - 当我使用 ng build 进行部署时,如何解决 Angular 项目中 vendor.js 中的错误语法
- unity3d - 使用行进立方体算法(体素)实现多纹理着色
- android - 如何检查是否为 TTS 下载了语言
- xslt - XSLT/XPath - 计算相邻节点
- java - 如何在 android 中将特定的用户代理与 (Magical) ExoPlayer 一起使用?
- python - 有没有办法使用 Selenium Python 的鼠标滚轮滚动网页?
- python - 如何使用 RecycleGridLayout 在 RecycleView 中使加载的小部件可滚动?
- php - 如何告诉正则表达式不要忽略嵌套匹配?