TypeScript - 私有变量和受保护变量之间的差异

Swe*_*abh 34 typescript

TypeScript privateprotected变量之间有什么区别?存在类似的问题,C#但我不确定两种语言中的概念是否相同.如果没有,了解差异将是有用的.

Nit*_*mer 42

它与其他OO语言相同.
私有方法/成员只能从课程内部访问.
受保护的方法/成员也可以从类内部访问,也可以扩展类.

class A {
    private x: number;
    protected y: number;

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    getX(): number {
        return this.x;
    }

    getY(): number {
        return this.y;
    }
}

class B extends A {
    multiply(): number {
        return this.x * this.y;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在课堂A上可以访问(私有)this.x和(受保护)this.y.
但是在课堂B上只有访问this.y并且this.x有这个错误:

属性'x'是私有的,只能在A类中访问

(你可以在游乐场看到错误)

但要理解的是,这只适用于打字稿.
在javascript中,任何引用该实例的人都可以访问这些成员.

  • 你的最后一句话是否意味着当转换为 JavaScript 时,我们会失去这个功能? (2认同)
  • @Qwerty 编译将以错误(不是警告)结束,无论是否有 ide。如果你没有 `--noEmitOnError` 标志,那么编译器仍然会创建编译后的 js 文件。使用这些时,在运行时所有“私有”或“受保护”的内容仍然完全可见,就像它是“公共”一样。 (2认同)

vcs*_*nes 8

protected在TypeScript中的工作方式与C#的工作方式非常相似.该打字稿发行说明文件它是这样:

类中新的protected修饰符的工作方式与熟悉的C++,C#和Java语言类似.类的受保护成员仅在声明它的类的子类中可见

private只允许您访问直接类类型.私有成员对子类不可见.


Hel*_*and 7

私有 方法

将成员标记为private时,无法从其包含的类外部对其进行访问。

保护 方法

保护的修饰符的作用很像私人所不同的是议员申报修改的保护,也可以派生类中访问。

one more一点要添加有关Protected variables

当基类变量受保护时,我们不能直接使用派生类中的变量。

例如:

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

class Mercedes extends Car{
    private noOfWheels: number;

    constructor(name: string, noOfWheels: number) {
        super(name);
        this.noOfWheels= noOfWheels;
    }

    public getIntro() {
        return `Hello, This is my ${this.name} and I have ${this.noOfWheels} wheels.`;
    }
}

let myCar= new Mercedes ("COOL Car", 4);
console.log(myCar.getIntro());  //Hello, This is my COOL Car and I have 4 wheels.
console.log(myCar.name); // Error!! , Property 'name' is protected and only accessible within class 'Car' and its subclasses.
Run Code Online (Sandbox Code Playgroud)

我们不能直接在Car类之外使用变量,我们仍然可以在Mercedes的实例方法中使用它,因为Mercedes是从Car派生的。

  • 呜!这个答案绝对应该是**`受保护的`**!Tx @伸出援助之手 (2认同)