从回调ES2015内部访问属性

Accessing properties from inside callback ES2015

本文关键字:访问 属性 内部 ES2015 回调      更新时间:2023-09-26

我在ES2015中使用的类与下面的片段相同:

class ProfileManager{
  constructor($http){
    this._http = $http;
    this.profile = {};
    }
  getUser(profile){
     this._http(`/api/users/${user.id}`).then(function(response){
        this.profile = response.data;    
        /*
         * Results in exception because "this uses the function's
         * "this" instead of the class' "this"
         */
     });
 }

我知道我可以通过在类外创建一个概要文件变量并在类中使用它来解决这个问题,但我想知道是否有更干净或更首选的方法可以在嵌套函数或回调中使用类属性。

ES6箭头函数不覆盖this

class ProfileManager {
  constructor($http) {
    this._http = $http;
    this.profile = {};
  }
  getUser(profile) {
     this._http(`/api/users/${user.id}`).then((response) => {
        this.profile = response.data; 
     });
 }