打字稿方法装饰器

时间:2018-01-11 22:57:27

标签: javascript typescript

我有这段代码

function changeFunc() {
    return function(target: any, title: string, descriptor: PropertyDescriptor) {

        descriptor.value = function () {
            console.log(this.name);
        };

        return descriptor;

    }
}


class Man {
    name: string = "asdsds";

    constructor(name: string) {
        this.name = name;
    }

    @changeFunc()
    getName() {
        console.log("Hello");
    }

}


var man = new Man('Manos Serifios');
man.getName();  

换句话说,我尝试(使用装饰器)进行更改 方法

getName() {  
    console.log("Hello");  
}  

用这个

function () {
    console.log(this.name);
}

但是this.name被评估为未定义。

如果我在控制台上记录“这个”,那么它似乎是正确的(实例人)。

4 个答案:

答案 0 :(得分:1)

在装饰器方法中没有特定对象实例的上下文。参数如下(来自https://www.typescriptlang.org/docs/handbook/decorators.html):

  

静态成员的类的构造函数,或实例成员的类的原型

     

会员的名字。

     

会员的属性描述符。

答案 1 :(得分:0)

只需将changeFunc()的返回值更改为胖箭头函数就可以解决问题。
那是因为

  

在箭头函数中,this保留了封闭词法上下文的this的值。

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

PS。我知道它已经很旧了,但是仍然有人会觉得有用。

答案 2 :(得分:0)

你可以做一点黑客。 替换您的代码

descriptor.value = function () {
  console.log(this.name);
};

用这个绝妙的技巧:

descriptor.value = function () {
  // Hack 
  const self = this as Man;
  console.log(self.name);
};

答案 3 :(得分:0)

@hackerman 的回答对我有用,因为这似乎只是打字问题。 另一种解决方案是为该函数主动定义 W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/flutter (31146): ***** initState is getting executed ***** I/flutter (31146): ***** sendVerificationEmail is getting executed ***** I/flutter (31146): Currently Logged In User (sendVerificationEmail): sas@gmail.com I/flutter (31146): ***** build is getting executed ***** I/flutter (31146): The assigned email address is sas@gmail.com I/flutter (31146): unhandled element metadata; Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#12622(), name: "assets/svg/email_sent.svg", colorFilter: null) I/flutter (31146): unhandled element sodipodi:namedview; Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#12622(), name: "assets/svg/email_sent.svg", colorFilter: null) W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/flutter (31146): ***** build is getting executed ***** I/flutter (31146): The assigned email address is sas@gmail.com D/FirebaseAuth(31146): Notifying id token listeners about user ( iISySN5DbtSqJ1cEO65ka3cro1i2 ). D/FirebaseAuth(31146): Notifying auth state listeners about user ( iISySN5DbtSqJ1cEO65ka3cro1i2 ). W/System (31146): Ignoring header X-Firebase-Locale because its value was null. W/DynamiteModule(31146): Local module descriptor class for providerinstaller not found. I/DynamiteModule(31146): Considering local module providerinstaller:0 and remote module providerinstaller:0 W/ProviderInstaller(31146): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0. I/flutter (31146): Exception thrown on Send Email Verification W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/flutter (31146): Null check operator used on a null value I/flutter (31146): ***** didChangeDependencies is getting executed ***** W/System (31146): Ignoring header X-Firebase-Locale because its value was null. W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/.nw.ap(31146): Background young concurrent copying GC freed 40900(2518KB) AllocSpace objects, 11(412KB) LOS objects, 36% free, 5214KB/8206KB, paused 7.797ms total 71.564ms W/System (31146): Ignoring header X-Firebase-Locale because its value was null. W/System (31146): Ignoring header X-Firebase-Locale because its value was null. W/System (31146): Ignoring header X-Firebase-Locale because its value was null. D/FirebaseAuth(31146): Notifying id token listeners about user ( iISySN5DbtSqJ1cEO65ka3cro1i2 ). I/flutter (31146): ***** checkEmailVerificationStatus is getting executed ***** I/flutter (31146): Currently Logged In User (checkEmailVerificationStatus): np.nw.io@gmail.com W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/flutter (31146): Is email verified? false I/flutter (31146): ***** checkEmailVerificationStatus is getting executed ***** I/flutter (31146): Currently Logged In User (checkEmailVerificationStatus): np.nw.io@gmail.com W/System (31146): Ignoring header X-Firebase-Locale because its value was null. I/flutter (31146): Is email verified? false 的类型:

this