1. ts 中类的定义
es5:
function Person(name) {
this.name = name;
this.run = function() {
console.log(this.name)
}
}
var p = new Person(‘张三‘)
p.run()
1.1 ts 中类的定义
class Person {
name:string; // 属性 前面省略了public 关键词
constructor(n:string) {
this.name = n;
}
getName():string {
alert(this.name)
return this.name;
}
setName(name:string):void {
this.name = name;
}
}
var p = new Person(‘赵四‘)
p.getName()
p.setName(‘王麻子‘)
p.getName()
1.2 ts 中类的继承
class Person { name:string; constructor(name:string) { this.name = name; } run():string { return `${this.name}在运动` } } class Women extends Person { constructor(name:string) { super(name); } run():string { return `${this.name}在运动 - 子类` } work():string { return `${this.name}在工作` } } var p = new Women(‘李斯‘) alert(p.run()) alert(p.work())
1.3 类的修饰符
// 类外部访问公有属性 class Person { public name:string; constructor(name:string) { this.name = name; } run():string { return `${this.name}在运动` } } var p = new Person(‘哈哈哈‘); alert(p.name)
class Person {
protected name:string;
constructor(name:string) {
this.name = name;
}
run():string {
return `${this.name}在运动`
}
}
class Web extends Person {
constructor(name:string) {
super(name);
}
work() {
alert(`${this.name}在工作`)
}
}
var w = new Web(‘许三多‘)
w.work()
1.4 静态属性 静态方法
1.5 多态
定义: 父类定义一个方法不实现,让继承它的子类去实现,每一个子类有不同的表现。
多态属于继承。
class Animal {
name:string;
constructor(name:string) {
this.name = name;
}
eat() {
console.log(‘吃东西‘)
}
}
class Dog extends Animal {
constructor(name:string) {
super(name);
}
eat() {
console.log(this.name + ‘吃狗粮‘)
}
}
class Cat extends Animal {
constructor(name:string) {
super(name);
}
eat() {
console.log(this.name + ‘吃猫粮‘)
}
}
var dog = new Dog(‘小狗‘)
dog.eat()
var cat = new Cat(‘小猫‘)
cat.eat()
1.6 抽象类
// ts 中的抽象类,它是提供其他类继承的基类,不能直接被实例化。
// 用 abstract 关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
// abstract 抽象方法只能放在抽象类里面
// 抽象类和抽象方法用来定义标准。标准:Animal 要求它的子类必须包含 eat 方法
原文:https://www.cnblogs.com/bulu08042/p/15037895.html