ts模拟类多继承类

  |  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 这里的实现方式是把类当做接口 使用implements继承
'use strict';
class Person {
name?: string;
grade?: number;
constructor(name: string, grade: number) {
this.grade = grade;
this.name = name;
}
sayHello() {
console.log('tag', `Helo ${this.name}!, ${this.grade}`);
}
}

// Student 类
class Student {
grade?: number;
constructor(grade: number) {
this.grade = grade;
}
test!: (name: string) => void;
study() {
this.test('1');
console.log('tag', ' I need Study!');
}
}

class SmartObject implements Person, Student {
// Person
name = 'person';
// Activatable
grade = 3;
sayHello!: () => void;
study!: () => void;
test(name: string) {
console.log('test', name);
}
static applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'test') derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
}

SmartObject.applyMixins(SmartObject, [Person, Student]);

export = SmartObject;

使用

1
2
3
4
'use strict';
import SmartObject from './index';
const smartObject = new SmartObject();
smartObject.study();
文章目录
  1. 1. 使用