这是使用传播运算符时失去上下文的代码。

查看功能“装饰器”。我丢失上下文时的行标记为“ ERROR”

/** MethodDecorator example */
class Account {
    public firstName: string;
    public lastName: string;

    public constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @decorator
    public sayMessage(msg: string): string {
        return `${this.firstName} ${this.lastName}: ${msg}`
    }
}

function decorator(target: any, key: string, desc: any): any {
    let originDesc = desc.value;

    desc.value = function(...args: any[]): any {
        return originDesc(...args); // ==> ERROR: context lost
        //return originDesc.apply(this, arguments); // ==> all OK
    };
    return desc;
}

let persone = new Account('John', 'Smith');
let message = persone.sayMessage('Hello world!');
console.log(message); // ==> undefined undefined: Hello world!


据我了解,originDesc(...args);等于originDesc.apply(this, arguments);,为什么我的上下文丢失了?

最佳答案

据我了解originDesc(... args);等于originDesc.apply(this,arguments);那么为什么背景会丢失?


不,不是。它等效于originDesc(args[0], args[1], /*etc.*/),它使用默认的this(松散模式下的全局对象,严格模式下的undefined)。

在该代码中,您需要使用.apply

originDesc.apply(appropriateThisValueHere, args);


.call

originDesc.call(appropriateThisValueHere, ...args);


根据代码中的此注释:


 //return originDesc.apply(this, arguments); // ==> all OK



appropriateThisValue将是this,因此:

originDesc.apply(this, args);


要么

originDesc.call(this, ...args);

09-13 09:11