JavaScript 的对象功能十分复杂,这个章节将会用 TypeScript 尝试厘清 JavaScript 的对象创建方式,并且利用面向对象观念来实作程序。
创建对象
JavaScript 创建对象的方式有三种,第一种是用大括号 {},第二种是用函数,第三种是用类别。在 TypeScript 中,任何对象的类型均属于 object 类型,而上一章介绍的数组和函数也是属于对象的一种。
大括号 {} 对象
在 JavaScript 中,可以直接用一对大括号,也就是 {} 来表示一个没有任何字段的「空对象」。
如下:
let o = {};
以上 o 变量保存的值为 {} 这个对象的参考(reference)。此时的 o 变量的类型也为 {}。如下:
let o: {} = {};
利用大括号产生出来的对象时,可以在大括号中直接以 key: value 的格式来添加对象属性(字段或方法)。如果有多个属性,就用逗号 , 隔开。例如:
let o = {
name: "David",
age: 18,
toString: function () {
return `${this.age}: ${this.name}`;
},
};
console.log(o.toString());
以上程序会输出:
以上程序的 o 变量的类型为 { name: string, age: number, toString: () => string }(用逗号 , 分隔属性),或 { name: string; age: number; toString: () => string }(用分号 ; 分隔属性)。toString 是 o 对象的方法,在这方法的程序实作区块中,使用了 this 关键字来表示目前这个对象的参考。这边要注意的是,如果是使用 Lambda 语法来定义函数,则无法使用 this 关键字来取得对象自身的参考。如下:
let o: { name: string, age: number, toString: () => string } = {
name: "David",
age: 18,
toString: () => `${this.age}: ${this.name}`,
};
console.log(o.toString());
以上程序会编译失败。
不过在 JavaScript 中,我们可以在对象的方法内直接访问用来存放对象参考的变量或常数。因此以上程序可以修改为:
let o: { name: string, age: number, toString: () => string } = {
name: "David",
age: 18,
toString: () => `${o.age}: ${o.name}`,
};
console.log(o.toString());
虽然我们在用大括号语法来创建对象时,属性的键值是直接填上一个名称,但这个名称实际上会被当作字符串来处理。所以以上程序其实就等同于:
let o: { name: string, age: number, toString: () => string } = {
"name": "David",
"age": 18,
"toString": () => `${o.age}: ${o.name}`,
};
console.log(o.toString());
在某些情况下,我们必须明确地用字符串来当作对象属性的键值。例如 student-number 这个名称,因为其中带有减号 -,所以必须要明确地用字符串来表示。如下:
let o: { name: string, age: number, toString: () => string, "student-number": string } = {
name: "David",
age: 18,
toString: () => `${o.age}: ${o.name}`,
"student-number": "B12345678",
};
console.log(o.toString());
在访问对象的属性时,也可以在对象后使用中括号 [] 语法,在中括号中传入要访问的字符串键值。如下:
let o: { name: string, age: number, toString: () => string, "student-number": string } = {
name: "David",
age: 18,
toString: () => `${o.age}: ${o.name}`,
"student-number": "B12345678",
};
console.log(o["toString"]());
console.log(o["student-number"]);
如果想要让对象拥有可选的属性,可以在定义对象类型时,在属性名称后面加上问号 ?。例如要将 student-number 这个属性变成可选的,程序如下:
let o: { name: string, age: number, toString: () => string, "student-number"?: string } = {
name: "David",
age: 18,
toString: () => `${o.age}: ${o.name}`,
};
console.log(o["student-number"]);
o["student-number"] = "B12345678";
console.log(o["student-number"]);
以上程序第 7 行,会输出 undefined,因为我们在创建 o 对象时,并没有替其添加 student-number 属性,如果查找的键值并不是该对象所拥有的话,就会回传 undefined。所以 student-number 这个属性的类型虽然被明确定义为 string,但它实际上是 string | undefined。
若想要用 Lambda 语法来实作可以回传大括号对象的函数,根据前面的章节提到的在 => 后直接加上表达式的语法,我们很可能会写出如下的程序:
let createObject = (name: string, age: number, studentNumber?: string) => {
name: name,
age: age,
toString: function () {
return `${this.age}: ${this.name}`;
},
"student-number": studentNumber,
};
let o1 = createObject("David", 18, "B12345678");
let o2 = createObject("Steven", 19);
然而以上程序有严重的语法错误,因为在 => 后接上大括号 {} 的话就变成是程序叙述区块了。为了解决这个问题,我们可以替大括号对象再围上小括号 ()。如下:
let createObject = (name: string, age: number, studentNumber?: string) => ({
name: name,
age: age,
toString: function () {
return `${this.age}: ${this.name}`;
},
"student-number": studentNumber,
});
let o1 = createObject("David", 18, "B12345678");
let o2 = createObject("Steven", 19);
注意这边的 toString 方法必须要使用 this 关键字来访问对象本身的属性。
对象的属性名称除了可以直接打上名称或是使用字符串之外,也可以用类型为 number、string 或 symbol 的变量和常数来代替,只要在定义属性名称时替这些变量和常数加上中括号 [] 包起来即可。例如:
const NAME = "name";
const AGE = "age";
const TO_STRING = "toString";
const STUDENT_NUMBER = "student-number";
let o: { [NAME]: string, [AGE]: number, [TO_STRING]: () => string, [STUDENT_NUMBER]: string } = {
[NAME]: "David",
[AGE]: 18,
[TO_STRING]: () => `${o[AGE]}: ${o[NAME]}`,
[STUDENT_NUMBER]: "B12345678",
};
console.log(o.toString());
console.log(o["student-number"]);
再例如:
const NAME = Symbol();
const AGE = Symbol();
const TO_STRING = Symbol();
const STUDENT_NUMBER = Symbol();
let o: { [NAME]: string, [AGE]: number, [TO_STRING]: () => string, [STUDENT_NUMBER]: string } = {
[NAME]: "David",
[AGE]: 18,
[TO_STRING]: () => `${o[AGE]}: ${o[NAME]}`,
[STUDENT_NUMBER]: "B12345678",
};
console.log(o[TO_STRING]());
console.log(o[STUDENT_NUMBER]);
值得注意的是,即便我们使用除了字符串以外的变量作为对象的属性名称,number 类型实际上在运行阶段仍会被自动转成字符串来使用。在 TypeScript 中,还是要遵照正确类型的键值来访问属性才行。
const i = "5";
const ii = 5;
const o = {
[i]: "567",
[ii]: "567",
};
for (const k in o) {
console.log(k, typeof k);
}
以上程序的运行结果为:
再来看看下面这个程序:
const i = 5;
const o = { [i]: "567" };
console.log(o[5]);
console.log(o["5"]);
以上程序可以通过编译,但是若将程序改为以下这样:
const i = 5;
const o = { [i]: "567" };
console.log(o[6]);
console.log(o["6"]);
以上程序,在严格模式下,第 5 行和第 6 行都会编译失败。这是因为 TypeScript 在严格模式下知道 o 对象此时只有一个属性名称为 5 的属性,所以用 6 或是 "6" 作为键值来访问属性才不行的吗?也不是,事实上,i 的类型是 5,而不是我们前面所说的 number,这是因为 i 是一个「常数」。所以 TypeScript 在严格模式下只允许访问 o 对象时须使用类型 5 或是 "5" 的键值来访问属性。有关于将定数作为类型的用法,会在之后的章节更加详细介绍。
若将 i 改用 let 或是 var 关键字来声明,会使得 i 的类型变为 number,则只有第 6 行会编译失败。但是,此时我们也不能使用 "5" 作为键值来访问 o 对象的属性。
let i = 5;
const o = { [i]: "567" };
console.log(o[6]);
console.log(o["5"]);
以上程序,在严格模式下,第 6 行会编译失败。
函数对象
在 JavaScript 中,用 function 关键字定义的函数都可以利用 new 关键字来创建出对象实体。例如:
function F() {
}
let a = new F();
console.log(typeof a);
console.log(a);
以上程序会输出:
F {}
F 是一个没有参数也没有程序叙述的函数,new F() 可以创建出一个未知类型的对象。
在严格模式下,以上程序会编译失败,因为编译器无法将未知类型的对象直接推论为 any。在这个情况下,我们也只能利用前面的章节介绍过的 as 关键字,将 F 函数强制转型为 any,来避开编译器的规则。
如下:
function F() {
}
let a = new (F as any)();
console.log(typeof a);
console.log(a);
事实上,F 函数的构造器即为自己本身,F 函数的参数就是构造器的参数,在 F 函数的主体中可以直接使用 this 关键字来访问到自身的属性。例如:
function F(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.toString = () => `${this.name}: ${this.age}`;
this.studentNumber = studentNumber;
}
let o1 = new (F as any)("David", 18, "B12345678");
let o2 = new (F as any)("Steven", 19);
console.log(o1.toString());
console.log(o2.toString());
以上程序在严格模式下会编译失败,因为 TypeScript 的编译器无法将 this 的类型自动推论为 any,所以在访问 this.name、this.age 等属性时会有问题。为了解决这个问题,我们必须要替 this 指定类型。
在 TypeScript 中,可以将 this 作为参数名称使其成为函数的第一个参数,如此一来就可以设置 this 的类型了。如下:
function F(this: any, name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.toString = () => `${this.name}: ${this.age}`;
this.studentNumber = studentNumber;
}
let o1 = new (F as any)("David", 18, "B12345678");
let o2 = new (F as any)("Steven", 19);
console.log(o1.toString());
console.log(o2.toString());
或是:
function F(this: {name: string, age: number, toString: () => string, studentNumber?: string}, name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.toString = () => `${this.name}: ${this.age}`;
this.studentNumber = studentNumber;
}
let o1 = new (F as any)("David", 18, "B12345678");
let o2 = new (F as any)("Steven", 19);
console.log(o1.toString());
console.log(o2.toString());
以上程序输出结果为:
Steven: 19
还记得我们在上一章有提到 symbol 类型的值可以拿来实作私有的属性吗?我们只要在对象的构造器中用 Symbol 函数创建 symbol 类型的值,来当对象属性的键值,这个属性就会是私有的,因为外部无法创建一个一模一样的 symbol 类型的值出来当作要查找的键值。
例如要将 F 函数产生出来的对象的 name 和 age 字段都变成私有的话,程序改写如下:
function F(this: any, name: string, age: number, studentNumber?: string) {
const NAME = Symbol();
const AGE = Symbol();
this[NAME] = name;
this[AGE] = age;
this.toString = () => `${this[NAME]}: ${this[AGE]}`;
this.studentNumber = studentNumber;
}
let o1 = new (F as any)("David", 18, "B12345678");
let o2 = new (F as any)("Steven", 19);
console.log(o1.toString());
console.log(o2.toString());
不过如果要使用私有属性的话,this 的类型貌似就只能是 any 了,除非我们把它做成双层函数,如下:
function F(name: string, age: number, studentNumber?: string) {
const NAME = Symbol();
const AGE = Symbol();
function inner(this: { [NAME]: string, [AGE]: number, toString: () => string, studentNumber?: string }, name: string, age: number, studentNumber?: string) {
this[NAME] = name;
this[AGE] = age;
this.toString = () => `${this[NAME]}: ${this[AGE]}`;
this.studentNumber = studentNumber;
}
return new (inner as any)(name, age, studentNumber);
}
let o1 = new (F as any)("David", 18, "B12345678");
let o2 = new (F as any)("Steven", 19);
console.log(o1.toString());
console.log(o2.toString());
在函数对象的构造器中回传的值,即为使用 new 关键字时创建出来的对象。如果函数的构造器不回传值,则会用 this 作为使用 new 关键字时创建出来的对象。
类别对象
JavaScript 的函数对象非常不适合在 TypeScript 上使用,因为类型实在是太不好处理了!还好在 ES6 之后,JavaScript 添加了类别对象的功能,使我们可以直接使用 class 关键字来定义类别。
在 TypeScript 中,类别的语法结构如下:
class 类别名称 {
字段1
字段2
...
字段n
构造器
方法1
方法2
...
方法n
}
字段的撰写方式类似使用 var、let、const 关键字来声明变量或常数那样,但不需要写上 var、let、const 关键字,并且在字段名称的后面可以加上问号 ? 来表示该字段为可选字段。字段、构造器和方法的撰写顺序可以随意,并不会影响程序的运作。类别不一定要明确写出构造器,如果不撰写构造器的话,会被当作是有一个无任何参数的构造器。
构造器和方法的撰写方式类似使用 function 关键字来创建函数那样,但不需要写上 function 关键字。
拿刚才撰写过的函数对象来举例:
function F(this: any, name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.toString = () => `${this.name}: ${this.age}`;
this.studentNumber = studentNumber;
}
以上程序可以用类别对象改写为:
class F {
name: string;
age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
若要创建类别 F 的对象实体,与函数对象一样,也是要使用 new 关键字。不过 TypeScript 可以正常推论类别的构造器,所以不需要再像函数对象那样用 as 关键字来转型了!而且产生出来的对象类型就是类别本身。
例如:
class F {
name: string;
age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o1: F = new F("David", 18, "B12345678");
let o2: F = new F("Steven", 19);
对于私有属性,我们也只要在属性名称前,加上 private 修饰子即可。如下:
class F {
private name: string;
private age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
以上程序将 F 类别的 name 和 age 对象字段的访问权限设为私有的了。
构造器也可以使用 private 来修饰,如果这样做的话,这个类别就无法在类别外部被实体化。
既然有 private 修饰子,那有 public 修饰子吗?当然有!public 修饰子可以用在构造器的参数上,能使该参数直接变成一般的对象属性,并且可以直接透过构造器参数来初始化,不必再在构造器主体中撰写 this.xxx = xxx 这样的程序叙述。
例如:
class F {
name: string;
age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: F = new F("David", 18, "B12345678");
console.log(o.name);
console.log(o.age);
console.log(o.studentNumber);
以上程序可以修改成:
class F {
constructor(public name: string, public age: number, public studentNumber?: string) {
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: F = new F("David", 18, "B12345678");
console.log(o.name);
console.log(o.age);
console.log(o.studentNumber);
对象的原型(Prototype)与继承(Inheritance)
事实上,我们刚才写的类别对象:
class F {
name: string;
age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
它其实更接近于以下这个函数对象:
function F(this: any, name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
F.prototype.toString = function() {
return `${this.name}: ${this.age}`;
};
直接在类别对象中定义的方法,都会变成类别本身的 prototype 属性下的方法。
当我们要访问一个对象的属性时,例如要访问 toString 这个属性好了,JavaScript 会先去寻找对象本身有没有 toString 属性,如果没有的话,就会去寻找该对象的上级对象的 prototype 属性下有没有 toString 属性。如果还是没有,就会去寻找这个上级对象的 prototype 属性下的 __proto__ 属性有没有 toString 属性。如果还是没有,就会去寻找这个上级对象的 prototype 属性下的 __proto__ 属性下的 __proto__ 属性下有没有 toString 属性。依此类推,直到找不到可用的 __proto__ 属性为止。此时若对象是数组,就会去找 Array 这个 JavaScript 内置对象的 prototype 属性下的 toString 属性,如果还是没有,就会去找 Object 这个 JavaScript 内置对象的 prototype 属性下的 toString 属性;若此时对象不是数组,就会直接去找 Object 的 prototype 属性下的 toString 属性。
顺带一提,number 类型的值在寻找属性的时候,会先去找 Number 这个 JavaScript 内置对象的 prototype 属性,再去找 Object 的 prototype 属性;string 类型的值在寻找属性的时候,会先去找 String 这个 JavaScript 内置对象的 prototype 属性,再去找 Object 的 prototype 属性。依此类推。
使用 new 关键字产生出来的函数对象实体,其上级对象即为该函数本身。如果我们要让函数对象去继承其它的函数对象或是类别的话,可以直接去设置函数的 prototype 属性的 __proto__ 属性为其它函数对象或是类别的 prototype 属性。
举例来说:
function User(this: { name: string, type: string }, name: string) {
this.name = name;
this.type = "user";
}
User.prototype.whoAmI = function () {
return `My name is ${this.name}. I am a ${this.type}.`;
};
function Human(this: { name: string, type: string }, name: string) {
User.apply(this, [name]);
this.type = "human";
}
Human.prototype.__proto__ = User.prototype;
function Robot(this: { name: string, type: string }, name: string) {
User.apply(this, [name]);
this.type = "robot";
}
Robot.prototype.__proto__ = User.prototype;
function Student(this: { name: string, type: string }, name: string) {
Human.apply(this, [name]);
this.type = "student";
}
Student.prototype.__proto__ = Human.prototype;
let o1 = new (User as any)("Unknown");
let o2 = new (Human as any)("David");
let o3 = new (Robot as any)("WALL-E");
let o4 = new (Student as any)("Steven");
console.log(o1.whoAmI());
console.log(o2.whoAmI());
console.log(o3.whoAmI());
console.log(o4.whoAmI());
以上程序,Student 继承 Human,Human 继承 User,Robot 继承 User。利用了函数提供的 apply 方法来指定要使用相同的 this 所保存的对象参考来调用函数。
运行结果如下:
My name is David. I am a human.
My name is WALL-E. I am a robot.
My name is Steven. I am a student.
当然,以上程序如果使用类别对象来改写的话,会变得易读许多。改写结果如下:
class User {
name: string;
type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
class Robot extends User {
constructor(name: string) {
super(name);
this.type = "robot";
}
}
class Student extends Human {
constructor(name: string) {
super(name);
this.type = "student";
}
}
let o1 = new User("Unknown");
let o2 = new Human("David");
let o3 = new Robot("WALL-E");
let o4 = new Student("Steven");
console.log(o1.whoAmI());
console.log(o2.whoAmI());
console.log(o3.whoAmI());
console.log(o4.whoAmI());
在类别名称后面加上 extends 关键字,可以指定该类别要继承的类别。在子类别的构造器中,必须要在第一个程序叙述使用 super 关键字来调用父类别的构造器。
如果我们把 User 类别的 type 对象字段改成私有的,确保其不能被外部程序更改的话,会发现其子类别均无法成功访问 type 对象字段而造成 TypeScript 编译错误。像这种需要让属性能够只公开到子类别的情况,我们要将属性的修饰子改为 protected,而不是 private。如下:
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
class Robot extends User {
constructor(name: string) {
super(name);
this.type = "robot";
}
}
class Student extends Human {
constructor(name: string) {
super(name);
this.type = "student";
}
}
let o1 = new User("Unknown");
let o2 = new Human("David");
let o3 = new Robot("WALL-E");
let o4 = new Student("Steven");
console.log(o1.whoAmI());
console.log(o2.whoAmI());
console.log(o3.whoAmI());
console.log(o4.whoAmI());
替对象的属性添加适合的访问修饰子,正是面向对象编程的封装(Encapsulation)观念。
判断对象是否属于指定的类别
既然对象有了继承关系,我们就很可能会需要在程序运行阶段去判断对象所属的类别。在 JavaScript 中,提供了 instanceof 关键字,可以用来判断一个对象是否属于指定的类别。
例如:
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
class Robot extends User {
constructor(name: string) {
super(name);
this.type = "robot";
}
}
class Student extends Human {
constructor(name: string) {
super(name);
this.type = "student";
}
}
const o1: User = new User("Unknown");
const o2: User = new Human("David");
const o3: User = new Robot("WALL-E");
const o4: User = new Student("Steven");
console.log(o1 instanceof User);
console.log(o2 instanceof User);
console.log(o3 instanceof User);
console.log(o4 instanceof User);
console.log(o4 instanceof Human);
console.log(o4 instanceof Robot);
console.log(o4 instanceof Student);
以上程序的运行结果如下:
true
true
true
true
false
true
以上程序第 36 行到第 39 行,由于 Human、Robot、Student 类别都继承 User 类别,因此它们的实体的类型也可以是 User。这就是面向对象的多态(Polymorphism)观念。
类别(静态)属性
除了将类别实体化出来后的对象能够拥有属性之外,我们也可以让类别本身也拥有属性。只要在撰写类别程序的时候,在属性名称前加上 static 关键字,即可使其成为类别属性。
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
static printInformation() {
console.log("User");
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
static printInformation() {
console.log("Human");
}
}
class Robot extends User {
constructor(name: string) {
super(name);
this.type = "robot";
}
static printInformation() {
console.log("Robot");
}
}
class Student extends Human {
constructor(name: string) {
super(name);
this.type = "student";
}
}
User.printInformation();
Human.printInformation();
Robot.printInformation();
Student.printInformation();
以上程序的输出结果如下:
Human
Robot
Human
类别属性是可以被继承的,但是我们无法透过类别实体化出来的对象来访问类别属性。如果要替类别属性加上访问修饰子,要添加在 static 关键字之前。
唯读字段
在撰写类别程序的时候,在字段名称前加上 readonly 关键字,即可使其成为唯读字段。
class User {
readonly name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
static printInformation() {
console.log("User");
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
static printInformation() {
console.log("Human");
}
}
class Robot extends User {
constructor(name: string) {
super(name);
this.type = "robot";
}
static printInformation() {
console.log("Robot");
}
}
class Student extends Human {
constructor(name: string) {
super(name);
this.type = "student";
}
}
User.printInformation();
Human.printInformation();
Robot.printInformation();
Student.printInformation();
若我们想尝试修改 User 或是其子类别的对象的 name 字段,就会编译错误。只有在类别自己的构造器中,才可以修改唯读字段。
如果有访问修饰子的存在,readonly 关键字要加在访问修饰子之后。如果有 static 关键字的存在,readonly 关键字要加在 static 关键字之后。
大括号对象也可以有唯读字段,只要在类型中的属性名称前加上 readonly 关键字就好。例如:
let o: { readonly name: string, readonly age: number, toString: () => string } = {
name: "David",
age: 18,
toString: () => `${o.age}: ${o.name}`,
};
函数(方法)多载
类别中的函数,或者说对象的方法,当然也可以多载。例如:
class F {
name: string;
age: number;
studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString(): string;
toString(includeStudentNumber: boolean): string;
toString(includeStudentNumber?: boolean) {
if (includeStudentNumber) {
if (typeof this.studentNumber === "string") {
return `${this.name}: ${this.age}, ${this.studentNumber}`;
}
}
return `${this.name}: ${this.age}`;
}
}
调用父类别的方法
super 关键字也可以用来调用父类别(被覆写前的)的方法。例如:
class S {
a() {
console.log("a");
}
b() {
console.log("b");
}
}
class C extends S {
a() {
console.log("A");
}
b() {
console.log("B");
}
ab() {
this.a();
super.b();
}
}
new C().ab();
以上程序会输出:
b
getter 和 setter
对于私有字段,我们可以透过对象方法来访问它。例如:
class User {
readonly name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
getType(): string {
return this.type;
}
setType(t: string) {
if (t.length > 0) {
this.type = t;
} else {
this.type = "user";
}
}
}
let user = new User("David");
console.log(user.getType());
user.setType("human");
console.log(user.getType());
以上 User 对象的 getType 方法即为一个「getter」,setType 方法即为一个「setter」。
事实上,若 TypeScript 的编译目标为 ES5 或是以上的版本的话,我们可以在类别的方法前加上 set 或是 get 关键字,来让该方法变成一个「getter」或一个「setter」,使该方法的属性名称变成「可以被安全访问的字段」。例如:
class User {
readonly name: string;
protected _type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
get type(): string {
return this._type;
}
set type(t: string) {
if (t.length > 0) {
this._type = t;
} else {
this._type = "user";
}
}
}
let user = new User("David");
console.log(user.type);
user.type = "human";
console.log(user.type);
被加上 set 或是 get 关键字的方法也可以设置访问修饰子,还可以在其前面加上 static 关键字使其变成静态属性。
any、object 与对象类型的转换
前面有提到过,在 TypeScript 中,任何对象的类型均属于 object 类型。object 类型表示非基本类型的值,它和 {} 类型一样无法直接访问对象本身的属性。不过两者并不相同,{} 类型还可以接受 1、"a" 等基本类型的值(只排除 null 和 undefined)。
我们在先前的章节也有提到过,any 可以用来表示任意类型,所以我们可以将任意对象转成 any 类型。
例如:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: any = new F("David", 18);
o.name = 18;
o.age = "David";
o.other = true;
以上程序,虽然 o 变量是 F 类别的对象,但它的类型被明确定义为 any,因此可以无限制地操作 F 对象的属性。
事实上,以上这个 F 类别的对象类型,也可以用 {readonly name: string, readonly age: number, readonly studentNumber?: string, toString: () => string } 来表示。例如:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: {readonly name: string, readonly age: number, readonly studentNumber?: string, toString: () => string} = new F("David", 18);
我们可以透过类型来「隐藏」对象的某些属性。例如要隐藏 studentNumber 属性:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: {readonly name: string, readonly age: number, toString: () => string} = new F("David", 18);
我们甚至可以把类型中的 readonly 关键字直接拿掉,让它的唯读字段变成可读写字段。
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: {name: string, age: number, toString: () => string} = new F("David", 18);
o.name = "Steven";
o.age = 19;
令人震惊的是,我们其实可以把任意值的类型改为其它完全不相关的类型,只要利用 any 来做中介转型即可。
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: { firstName: string, lastName: string } = new F("David", 18) as any;
o.firstName = "Steven";
o.lastName = "Nigel";
以上程序是可以通过编译并且成功运行的。
由于 TypeScript 的类型并不是这么的安全,因此在使用冒号 : 接上类型来明确定义变量或是参数的类型时,或是使用 as 关键字接上类型来进行转型时,要特别注意原本值的类型。
能够任意添加属性的对象类型
any 类型除了能够让我们自由访问对象的属性之外,TypeScript 还提供了另一种比较安全的方式。先看以下程序:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: {name: string, age: number, toString: () => string} = new F("David", 18);
如果我们想要让 o 对象能够在保有类别 F 的属性限制下,添加额外的任意属性,可以在其类型上加上这样的属性 [_: string]: any。如下:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
let o: { name: string, age: number, toString: () => string, [_: string]: any } = new F("David", 18);
o.a = 1;
o.b = "2";
o.c = false;
[_: string]: any 语法看起来很怪异,它的意思是:这个类型的所有对象属性的键值都必须是 string,且值的类型可为任意类型。属性的键值可以使用数值或是字符串,大部份的情况下会用字符串,就算是用数值也是可以用字符串来访问属性。在类型的属性中有了 [_: string]: any 后,我们就可以替这个类型的对象添加任意属性,存放任意类型的值了!
再举一个例子,如果要设计一个属性值只能是数值的对象,程序如下:
let o: { [_: string]: number } = {};
o.a = 1;
o.b = 2;
利用 is 关键字来缩减类型范围
还记得上一章中,我们写的以下这段程序吗?
function save(path: string, data_force?: string | boolean, force?: boolean): boolean {
let data;
const t_data_force = typeof data_force;
if (t_data_force === "undefined") {
data = "Hello, world!";
force = false;
} else if (t_data_force === "boolean") {
data = "Hello, world!";
force = data_force as boolean;
} else { // string
data = data_force;
}
const fs = require("node:fs");
if (fs.existsSync(path)) {
if (force) {
fs.unlinkSync(path);
} else {
return false;
}
}
fs.writeFileSync(path, data);
return true;
}
为了让我们的程序更安全,我们应该要尽量避免转型的发生。TypeScript 提供了 is 关键字,可以用在函数的回传值上,来帮助 TypeScript 的编译器限缩值的类型范围。
以上程序,由于 data_force 参数的类型为 string | boolean | undefined,所以我们其实可以加入以下利用了 is 关键字实作的两个函数,来让编译器能够正确判断 data_force 的类型。
function save(path: string, data_force?: string | boolean, force?: boolean): boolean {
let data;
const t_data_force = typeof data_force;
function isUndefined(data_force?: string | boolean): data_force is undefined {
return t_data_force === "undefined";
}
function isBoolean(data_force?: string | boolean): data_force is boolean {
return t_data_force === "boolean";
}
if (isUndefined(data_force)) {
data = "Hello, world!";
force = false;
} else if (isBoolean(data_force)) {
data = "Hello, world!";
force = data_force;
} else { // string
data = data_force;
}
const fs = require("node:fs");
if (fs.existsSync(path)) {
if (force) {
fs.unlinkSync(path);
} else {
return false;
}
}
fs.writeFileSync(path, data);
return true;
}
题外话,如果值的类型全都被编译器限缩到没有的话,会发生什么事呢?
例如:
function foo(x: string | number): boolean | void {
const t_x = typeof x;
function isString(data_force: string | number): data_force is string {
return t_x === "string";
}
function isNumber(data_force: string | number): data_force is number {
return t_x === "number";
}
if (isString(x)) {
return true;
} else if (isNumber(x)) {
return false;
}
}
当程序运行完第 16 行之后,x 变量的类型是什么?它的类型其实是 never!
function foo(x: string | number): boolean | void {
const t_x = typeof x;
function isString(data_force: string | number): data_force is string {
return t_x === "string";
}
function isNumber(data_force: string | number): data_force is number {
return t_x === "number";
}
if (isString(x)) {
return true;
} else if (isNumber(x)) {
return false;
}
let xx: never = x;
}
在 TypeScript 中,用 never 来表示「没有类型」。
判断对象是否有指定的属性
in 关键字,除了可以用来制作 for-in 循环之外,还可以判断一个对象是否有指定的属性。例如:
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
const o1 = new User("Unknown");
const o2 = new Human("David");
console.log("name" in o1);
console.log("whoAmI" in o1);
console.log("name" in o2);
console.log("whoAmI" in o2);
console.log(o1.hasOwnProperty("name"));
console.log(o1.hasOwnProperty("whoAmI"));
console.log(o2.hasOwnProperty("name"));
console.log(o2.hasOwnProperty("whoAmI"));
以上程序会输出:
true
true
true
true
false
true
false
对象的 hasOwnProperty 方法可以判断对象是否自己拥有(而非透过 prototype)指定的属性。其实在使用 for-in 循环来走访对象的属性时,通常还需要使用 hasOwnProperty 方法来过滤掉非自身的属性。
例如:
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
const o = new Human("David");
for (const key in o) {
console.log(key);
}
以上程序会输出:
name
constructor
whoAmI
而我们通常在使用 for-in 循环时,只是要得到对象本身拥有的属性,所以要把程序写成:
class User {
name: string;
protected type = "user";
constructor(name: string) {
this.name = name;
}
whoAmI() {
return `My name is ${this.name}. I am a ${this.type}.`;
}
}
class Human extends User {
constructor(name: string) {
super(name);
this.type = "human";
}
}
const o = new Human("David");
for (const key in o) {
if (o.hasOwnProperty(key)) {
console.log(key);
}
}
以上程序会输出:
name
您可能会觉得很奇怪,既然对象有 hasOwnProperty 方法,为什么 hasOwnProperty 在使用 for-in 循环的时候不会被走访呢?这是因为 JavaScript 的属性其实是有一些「选项」可以设置的,能够被 for-in 循环走访到的属性,它的 enumerable 选项必须要被设为 true(默认值正是 true)。然而 hasOwnProperty 属性的 enumerable 选项是设为 false,所以它不会被 for-in 循环走访。
JavaScript 内置的 Object 对象,提供了 defineProperty 和 defineProperties 方法,可以用比较低级的方式来设置任意类型的值的属性。由于这部份并不是本系列文章的范围,在此就点到为止。
总结
在这个章节中,我们学到了大括号对象、函数对象和类别对象,这三种 JavaScript 对象的创建方式,稍微掌握了面向对象编程的方式,也了解了 TypeScript 可怕的转型机制,然后还学会了 instanceof、is 和 in 关键字的用法。在下一个章节中,要来学习 TypeScript 提供的界面用法。
