TypeScript private和protected变量之间有什么区别?存在类似的问题,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中,任何引用该实例的人都可以访问这些成员.
私有 方法:
将成员标记为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派生的。
| 归档时间: |
|
| 查看次数: |
21456 次 |
| 最近记录: |