编译后的JavaScript文件在类型脚本类中使用访问修饰符时,在类构造函数中有重复的变量声明

fae0ux8s  于 2023-05-21  发布在  Java
关注(0)|答案(2)|浏览(66)

我正在尝试构建一个类型脚本类,其中有一些属性与访问修饰符,如下面的代码。

class Coder {
    age : number;

    constructor(
    public readonly name : string,
    age : number,
    public lang : string,
    private address : string,
    protected id : number = 234
    )
    {
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }

    getName()
    {
        return `My name is ${this.name}`;
    }
}

let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');

// Not possible as name is readOnly
// coder.name = 'Golu';

但是编译后的代码在构造函数中有一个具有重复属性标记的类,如下面的代码所示。
一旦我试图删除任何修饰符,那么重复的属性也会在编译的js文件中被删除(参见age属性)。

"use strict";
class Coder {
    constructor(name, age, lang, address, id = 234) {
        this.name = name;
        this.lang = lang;
        this.address = address;
        this.id = id;
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }
    getName() {
        return `My name is ${this.name}`;
    }
}
let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');
// Not possible as name is readOnly
// coder.name = 'Golu';

不知道为什么会发生这种情况,因为它只是违反了DRY规则。

vs91vp4v

vs91vp4v1#

这是因为在构造函数中传递的变量上的任何访问修饰符都编译为该类上的声明和构造函数中的赋值。

class Test {
   constructor(public whatever: string){}
}

class Test {
   public whatever: string;
   constructor(whatever: string) {
      this.whatever = whatever;
   }
}

所以如果你写

class Test {
   constructor(public whatever: string){
      this.whatever = whatever;
   }
}

它就相当于

class Test {
   public whatever: string;
   constructor(whatever: string) {
      this.whatever = whatever; 
      this.whatever = whatever;
   }
}
htrmnn0y

htrmnn0y2#

当使用修饰符时,您不需要自己显式地Map变量,因为重复的原因是您自己的代码。使用访问修饰符时删除此选项:

this.name = name;

相关问题