上下文中的对象 "this" 不正确

Incorrect object "this" on context

我在以下结构的助手 class 上丢失了“This”对象的上下文,我不明白为什么。

getAll 方法中,this 对象正在引用位于 servicesDict 主要组件上的数组。

我希望 this 对象引用 Entity1Utils class。

export class Entity1Utils {
    public getAll(context) {
        this.buildQueryParams();
        // this "this" refers to the object { id: 'entity1', method: this.entity1Utils.getAll }
        // located on servicesDict at ManagementComponent
    }

    private buildQueryParams() {
        // logical code
    }
}


@Component({
    selector: 'app-management',
    templateUrl: './management.component.html',
    styleUrls: ['./management.component.css']
})

export class ManagementComponent implements OnInit {
    private entity1Utils: Entity1Utils;
    private servicesDict: any;

    constructor() {
        this.entity1Utils = new Entity1Utils();

        this.servicesDict = [
            { id: 'entity1', method: this.entity1Utils.getAll }
        ];
    }
}

嗯,你可以使用 bind,例如:

method: this.entity1Utils.getAll.bind(this.entity1Utils)

一般来说,函数内的范围(this 指向的范围)由调用该方法的对象决定。

foo.doSomething() // inside doSomething, 'this' is foo
const method = foo.doSomething;
method(); // 'this' is undefined
const obj = { method: foo.doSomething }
obj.method() // 'this' is obj

您正在传递对 方法本身 的引用,与 class:

的实例分离
{ method: this.entity1Utils.getAll } // the getAll method itself

因此,当下游调用它时,它会将其作为 servicesDict 上的方法调用:

const service = serviceDict[0];

// 'getAll' invoked on the serviceDict entry, so inside
// the method 'this' points to the serviceDict entry
service.method() 

您可以通过使该方法成为箭头函数来解决此问题,将其绑定到当前作用域:

getAll = context => { ... }

或者通过创建一个新的匿名内联箭头函数来保留作用域:

{ method: (...args) => this.entity1Utils.getAll(...args) }

或者通过显式绑定:

{ method: this.entity1Utils.getAll.bind(this.entity1Utils) }