javascript - 来自匿名函数的 JavaScript 字段访问
问题描述
如何从方法内的匿名函数中访问字段?就像在这个例子中:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
这将导致“this”未定义的错误。非常感谢您,搜索了几个小时后,我在网上找不到答案。最好的,列夫
解决方案
在您的匿名函数中,this
绑定到该函数;它不再指类。
请改用箭头函数,它没有自己的this
绑定。
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
或者,您可以使用类似.call()
,.apply()
或.bind()
:
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();
推荐阅读
- sql - SQL Server big tables or store data in a xml field
- php - PHP Get peak from dataset with value and timestamp
- javascript - Rendering complex JSON/Javascript Objects in React
- ios - 在 TableViews 的上下文中,swift 中的“编辑模式”是什么?
- angular - Ionic unable to change active segment button color
- python - BeautifulSoup selector returning empty list
- java - Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M5:test (default-test) on project
- nuxt.js - nuxt js - terser - 超出了调用重试次数
- r - R - 加载多个 csv 文件并从名称中删除 .csv
- python-3.x - AWS Lambda 层 - 尽管有任何代码更改,版本都会增加