TypeScript类实例中this为undefined无法访问成员方法如何解决
问题根源
报错核心原因是 Array.forEach 回调中使用了普通匿名函数,普通函数的this指向是运行时动态绑定的,非严格模式下指向全局对象,严格模式下直接为undefined,因此无法访问到类实例的getAddress方法。
可行解决方案
下面是三种常用的修复方案,优先推荐第一种:
方案1:使用箭头函数代替普通回调(推荐)
箭头函数不会创建自己的this,会继承外层作用域的this指向,也就是类实例本身,修改forEach的回调写法即可:
Array.isArray(searchResultItems) ? searchResultItems.forEach((param) => { companyArray.push(this.getAddress(param.organisation)) }) : companyArray.push(this.getAddress(searchResultItems.organisation))
方案2:为forEach指定this参数
Array.forEach支持传入第二个参数作为回调函数的this指向,直接传入当前类实例的this即可:
Array.isArray(searchResultItems) ? searchResultItems.forEach(function(param) { companyArray.push(this.getAddress(param.organisation)) }, this) : companyArray.push(this.getAddress(searchResultItems.organisation))
方案3:提前缓存this指向
在函数开头提前将类实例的this赋值给一个临时变量,回调中使用该变量访问方法:
public getDataFromResponse(response: any) { const self = this; // 提前缓存this var companyArray = []; var searchResult = response["s:Envelope"]["s:Body"].SearchResponse.SearchResult; if (searchResult) { var searchResultItems = searchResult.uidEntitySearchResultItem; try { Array.isArray(searchResultItems) ? searchResultItems.forEach(function(param) { companyArray.push(self.getAddress(param.organisation)) }) : companyArray.push(self.getAddress(searchResultItems.organisation)) } catch(err) { console.log(err); } } return companyArray; }
额外注意事项
如果你的getDataFromResponse方法是被作为回调参数传递给其他函数调用(比如接口请求回调、事件监听回调),还需要保证方法本身的this指向正确,可以用两种方式处理:
- 在构造函数中绑定this:
constructor() { this.getDataFromResponse = this.getDataFromResponse.bind(this); }
- 将方法定义为类的箭头函数属性:
public getDataFromResponse = (response: any) => { // 原有逻辑 }
内容的提问来源于stack exchange,提问作者Paul Richardson
相关产品推荐
相关产品推荐

