【发布时间】:2019-01-01 06:26:46
【问题描述】:
我目前正在学习 TypeScript 课程(我在 OOP 方面没有太多经验)。
下面的sn-p来自https://www.typescriptlang.org/docs/handbook/classes.html中的classes章节
事情是这样的:
我知道它不应该直接访问受保护的属性“名称”,如console.log(howard.name),我知道通过派生类的方法访问它应该是可以的。
当我在 TypeScript 上编译它时,我确实收到了一条错误消息。但事实是,当我在浏览器上打开生成的 JS 文件(已编译)时,我可以在 Console 中看到输出,就像它是公共属性一样。
这在 OOP 中正常吗?如果在 JS 编译文件中无论如何都可以访问它们,为什么还要在 TypeScript 中创建具有受保护/私有属性的类?
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error
【问题讨论】:
-
department是员工私有的,因此getElevatorPitch()方法可以访问它 -
类型脚本的重点是为JS添加更多结构。编译后的 JS 总是与 Typescript 不同,因为它不一样。如果你不想使用类,如果你想使用 js,使用 typecipt 并将其编译为 js。
-
感谢您的评论!我知道。这是意料之中的。我没想到的是 JS 文件显示
console.log(howard.name);在控制台中输出“霍华德”。因为 name 属性应该受到保护。
标签: javascript typescript class oop