传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从ECMAScript 6开始,JavaScript程序员将能够使用基于类的面向对象的方式。
一个简单的小例子
我们在es6中定义一个类需要这么做:
class Animal {
constructor(type){ //构造函数,对象私有的东西
this.type = type;
}
eat(){//方法
console.log('i can eat food')
}
}
在TS中,我们可以这么做:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
public sayHi() {
return `My name is ${this.name}`;
}
}
let a = new Animal("Jack");
console.log(a.sayHi()); // My name is Jack
我们可以看到,和es中类的构造几乎是差不多的。而至于这里的public是什么,先不用着急,下面会讲到。
类的继承
ES6中类的继承是这么实现的:
class Animal {
constructor(type){
this.type = type;
}
eat(){
Animal.say()
console.log('i can eat food')
}
static say(){
console.log('i can say english')
}
}
class Dog extends Animal { //dog是Animal的子类
super(type) //初始化父类构造函数
//如果子类中也有自己的属性,需要写构造函数
constructor(type){
super(type) //必须放在最前面,type可以是亦是,可以是固定的
this.weight = 5;
}
}
let dog = new Dog('dog')
dog.eat()
//log
//i can say english
//i can eat food
在TS中,我们需要这么写:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
public sayHi() {
return `My name is ${this.name}`;
}
}
class Cat extends Animal {
constructor(name: string) {
super(name); // 调用父类的 constructor(name)
console.log(this.name);
}
public sayHi() {
return "Meow, " + super.sayHi(); // 调用父类的 sayHi()
}
}
官方给我们提供了一个看似很复杂的例子,我可以看看一下:
class Animal {
public name: string;
constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
public move(distanceInMeters: number = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
public move(distanceInMeters: number = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
心算一下它的运行结果,再自己试试看
public private 和 protected
public
修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是public
的private
修饰的属性或方法是私有的,不能在声明它的类的外部访问protected
修饰的属性或方法是受保护的,它和private
类似,区别是它在子类中也是允许被访问的
public
public我们在上面的例子已经用到了很多了,这里就不再演示新的示例了。
private
很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private
了
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
}
let a = new Animal("Jack");
此时的name属性在外部就是无法访问的了,只要访问编译就会报错。
ypeScript使用的是结构性类型系统。 当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的。
然而,当我们比较带有private
或protected
成员的类型的时候,情况就不同了。 如果其中一个类型里包含一个private
成员,那么只有当另外一个类型中也存在这样一个private
成员, 并且它们都是来自同一处声明时,我们才认为这两个类型是兼容的。 对于protected
成员也使用这个规则。
官方为我们举了个很好的例子
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor() { super("Rhino"); }
}
class Employee {
private name: string;
constructor(theName: string) { this.name = theName; }
}
let animal = new Animal("Goat");
let rhino = new Rhino();
let employee = new Employee("Bob");
animal = rhino;
animal = employee; // 错误: Animal 与 Employee 不兼容.
这个例子中有Animal
和Rhino
两个类,Rhino
是Animal
类的子类。 还有一个Employee
类,其类型看上去与Animal
是相同的。 我们创建了几个这些类的实例,并相互赋值来看看会发生什么。 因为Animal
和Rhino
共享了来自Animal
里的私有成员定义private name: string
,因此它们是兼容的。 然而Employee
却不是这样。当把Employee
赋值给Animal
的时候,得到一个错误,说它们的类型不兼容。 尽管Employee
里也有一个私有成员name
,但它明显不是Animal
里面定义的那个。
protected
protected
修饰符与private
修饰符的行为很相似,但有一点不同,protected
成员在派生类中仍然可以访问。
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); // 错误
我们不能在Person
类外使用name
,但是我们仍然可以通过Employee
类的实例方法访问,因为Employee
是由Person
派生而来的。
构造函数也可以被标记成protected
。 这意味着这个类不能在包含它的类外被实例化,但是能被继承
class Person {
protected name: string;
protected constructor(theName: string) { this.name = theName; }
}
// Employee 能够继承 Person
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");
let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
readonly
可以使用readonly
关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
class Octopus {
readonly name: string;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
参数属性
简单举一个例子吧:
class Animal {
constructor(private name: string) { }
move(weight: number) {
console.log(`${this.name} moved ${weight}m.`);
}
}
或许,我们可以简单的理解为,就是将声明与赋值合到了一处了。
getter && setter
如果对es6足够熟悉的话,应该是了解es6中对于class的get 与set 的
es6中,我们是这样使用的:
let _age = 4;
class Animal {
constructor(type){ //构造函数,对象私有的东西
this.type = type;
},
get age(){ //属性--只读
return _age;
}
set age(val){ //属性--可以修改
if(val <8 && val > 4){
_age = val //这里不可以使用this.age=val,会陷入死循环,即返回值与出入口的名字不可以一样
}
}
eat(){//方法
console.log('i can eat food')
}
}
可以明显的看出来,这里使用的闭包的方法,这是因为es6目前还不支持我们直接设置私有属性。
在TS中,我们一般这么写:
let passcode = "secret passcode";
class Employee {
private FullName: string;
get fullName(): string {
return this.FullName;
}
set fullName(newName: string) {
if (passcode && passcode === "secret passcode") {
this.FullName = newName;
} else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
只带有
get
不带有set
的存取器自动被推断为readonly
。 这在从代码生成.d.ts
文件时是有帮助的,因为利用这个属性的用户会看到不允许够改变它的值。
静态属性 && 静态方法
如果你了解过es6中类的静态方法的话,那么你在这里应很轻松就可以了解掌握TS中类的静态方法。
在这里不会去讲述类的静态属性和静态方法,只会介绍简单的小例子,如果不清楚类的静态方法和静态属性可以参考es6的概念。
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
这里演示了静态属性的使用,下面将会再演示一个静态方法的使用案例,如果还是不清楚 ,我想你需要去补一补es6了。
class Animal {
private static say() { // static 定义静态方法
console.log("i can say english");
}
constructor(public type: string) {
this.type = type;
}
public eat() {
Animal.say(); // 引用静态方法
console.log("i can eat food");
}
}
let dog = new Animal("dog");
dog.eat();
// log
// i can say english
// i can eat food
抽象类
- 抽象类做为其它派生类的基类使用。
- 它们一般不会直接被实例化。
不同于接口,抽象类可以包含成员的实现细节。
abstract
关键字是用于定义抽象类和在抽象类内部定义抽象方法。
abstract class Animal {
constructor(public name: string) {
}
public printName(): void {
console.log("Animal's name: " + this.name);
}
public abstract printAge(): void; // 必须在派生类中实现
}
class Dog extends Animal {
constructor(public age: number) {
super("er huo"); // 在派生类的构造函数中必须调用 super()
this.age = age;
}
public printAge(): void {
console.log("ten years old");
}
public printWeight(): void {
console.log("error...");
}
}
let lees: Animal; // 允许创建一个对抽象类型的引用
lees = new Animal(); // 错误: 不能创建一个抽象类的实例
lees = new Dog(10); // 允许对一个抽象子类进行实例化和赋值
lees.printName();
lees.printAge();
lees.printWeight(); // 错误: 方法在声明的抽象类中不存在
抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。 抽象方法的语法与接口方法相似。 两者都是定义方法签名但不包含方法体。 然而,抽象方法必须包含
abstract
关键字并且可以包含访问修饰符