枚举
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName); // 显示'Green'因为上面代码里它的值是2
编译后
var Color;
(function (Color) {
Color[Color["Red"] = 1] = "Red";
Color[Color["Green"] = 2] = "Green";
Color[Color["Blue"] = 3] = "Blue";
})(Color || (Color = {}));
var colorName = Color[2];
console.log(colorName);
此时Color对象内部结构为
image.png
所以Color[2]打印的结果会为Green
ps:解释赋值原理
var a
console.log(a="abc") //打印的结果为abc
//所以
Color[Color["Red"] = 1] = "Red";
//Color["Red"] = 1赋值完成后会演变成
Color[1] = "Red";
//所以最终枚举对象的结构才会如上图所示
private 和 protected 的共同的点以及不同点
共同点:
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
let van= new Person("Van")
console.log(van.name)
//这时候编译会发生错误
class Animal{
private name: string;
constructor(name: string) { this.name = name; }
}
let dolphin= new Animal("Dolphin")
console.log(dolphin.name)
//这时也会出现编译错误的问题
//证明:不管是protected 或是 private 描述的成员都不可以在类外进行调用
不同点:
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());
//此时将ts文件编译,不会有任何问题
如果将父类(超类)的name属性前置修饰符从protected 修改成 private 如:
class Person {
private 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());
//那么这时候编译该ts文件就会报错
//结论:如果父类(超类)的成员修饰符为protected 那么该成员可以在子类中被调用(如:子类中的getElevatorPitch方法)
//而如果父类(超类)的成员修饰符为private 那么该成员将不可以在子类中被调用
网友评论