(1)类的定义 (类定义了一件事物的抽象特点,包含了它的属性和方法)
class Cat3 {
name: string;
color: string;
constructor(name,color) {
this.name = name;
this.color = color;
}
eat() { // 原型上的方法
console.log("吃")
}
}
let c3 = new Cat3("jeck","red")
(2)类的继承(extends)
class Animal { // 动物类 犬类 和猫科类
type:string;
constructor(type) {
this.type = type
}
eat() {
console.log("吃")
}
say() {
console.log("叫")
}
}
class Dog extends Animal { // Dog类继承动物Animal类
name: string;
age: number;
constructor(type,name,age) {
super(type) // super关键字,在子类构造函数中调用父类,科传递参数
this.name = name
this.age = age
}
action() {
console.log("....")
}
}
var dog = new Dog("动物","狗狗",4)
####(3)类的修饰符
- 1 static 静态方法 不需要实例化 可以直接通过类来调用
class Obj {
static str:string = 'abc';
// constructor(str) {
// this.str = str
// }
static action() {
console.log("......")
}
}
Obj.action();
Obj.str;
- 2 public 修饰的属性或者方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是public
class Obj1 {
public name;
public constructor(name) {
this.name = name
}
public action() { // 只能在类的内部使用
return this.name
}
}
let obj1 = new Obj1("tom");
obj1.name;
- 3 private 私有的 修饰的属性或者方法是私有的,不能在声明它的类的外部访问
class Obj1 {
public name;
public constructor(name) {
this.name = name
}
private action() { // 只能在类的内部使用
return this.name
}
}
let obj1 = new Obj1("tom");
obj1.name;
obj1.action; // 报错的
效果图如下
- 4 protected 受保护的,和private相似,区别在于它在类中或者子类中也是允许被访问的,外部是不可以访问的
class Obj2 {
protected name;
public constructor(name) {
this.name = name;
}
protected action() {
this.name;
}
}
var obj2 = new Obj2("tom")
obj2.action() // 报错
效果图如下
class Obj2 {
protected name;
public constructor(name) {
this.name = name;
}
protected action() {
this.name;
}
}
var obj2 = new Obj2("tom")
class Obj22 extends Obj2 {
constructor(name) {
super(name);
}
say() { // 只能在子类访问,不能在外部访问
return this.action()
}
}
var obj22 = new Obj22("jeck")
obj22.action()
效果图如下:
(4)类和接口
- 什么是接口,接口是对象的形状就行描述,就是对对象就行约束
interface IObj4 {
name: string,
action():string, // 返回值为string
}
let iobj2:IObj4 = { // 强制指定类型
name: '张三',
action() {
return '123'
}
}
- 接口继承接口 使用extends
interface Iobj11 {
name: string,
action: () => void
}
interface Iobj22 {
say():void
}
interface Iobj33 extends Iobj11,Iobj22 {
age:number,
}
let obj33:Iobj33 = {
name:"张三",
age: 18,
action() {
console.log(`我叫${this.name}`)
},
say() {
console.log(`我会说中国话`)
}
}
(5)类实现接口,使用implements实现接口继承
// 比如说猫和老虎吧,他们有一个共同的属性就是属于猫科动物,这个时候就可以把特性提取成接口
interface IAction { // 都会爬树
action()
}
interface ISay { // 都会叫
say()
}
class Animals { // 公共的猫科动物
}
class Cats extends Animals implements IAction,ISay { // 猫是子类
action() {
console.log("爬树")
}
say() {
console.log("喵喵")
}
}
class Tigers extends Animals implements IAction,ISay { // 老虎是子类
action() {
return console.log("爬树")
}
say() {
console.log("喵喵")
}
}