枚舉
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName); // 顯示'Green'因?yàn)樯厦娲a里它的值是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);
此時(shí)Color對(duì)象內(nèi)部結(jié)構(gòu)為
所以Color[2]打印的結(jié)果會(huì)為Green
ps:解釋賦值原理
var a
console.log(a="abc") //打印的結(jié)果為abc
//所以
Color[Color["Red"] = 1] = "Red";
//Color["Red"] = 1賦值完成后會(huì)演變成
Color[1] = "Red";
//所以最終枚舉對(duì)象的結(jié)構(gòu)才會(huì)如上圖所示
private 和 protected 的共同的點(diǎn)以及不同點(diǎn)
共同點(diǎn):
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
let van= new Person("Van")
console.log(van.name)
//這時(shí)候編譯會(huì)發(fā)生錯(cuò)誤
class Animal{
private name: string;
constructor(name: string) { this.name = name; }
}
let dolphin= new Animal("Dolphin")
console.log(dolphin.name)
//這時(shí)也會(huì)出現(xiàn)編譯錯(cuò)誤的問(wèn)題
//證明:不管是protected 或是 private 描述的成員都不可以在類外進(jìn)行調(diào)用
不同點(diǎn):
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());
//此時(shí)將ts文件編譯,不會(huì)有任何問(wèn)題
如果將父類(超類)的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());
//那么這時(shí)候編譯該ts文件就會(huì)報(bào)錯(cuò)
//結(jié)論:如果父類(超類)的成員修飾符為protected 那么該成員可以在子類中被調(diào)用(如:子類中的getElevatorPitch方法)
//而如果父類(超類)的成員修飾符為private 那么該成員將不可以在子類中被調(diào)用