-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils-classes.mjs
38 lines (38 loc) · 1.23 KB
/
utils-classes.mjs
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
/**
* Usage:
* class A{}; class B{}; class C extends inherit(A,B){}
*
* If there are duplicate function names, only the latest in the classes list will be used.
*
* @typedef {new(...args:any[])=>any} class
*
* @param {...class} classes
* @returns {class}
*/
export function inherit(...classes) {
// Combine methods and properties
class Combined extends classes[0] {
constructor(/**@type {any[]}*/...args) {
super(...args)
classes.slice(1).forEach(base => {
Object.assign(this, new base())
Object.getOwnPropertyNames(base.prototype).forEach(prop => {
if (prop !== 'constructor') {
const descriptor = Object.getOwnPropertyDescriptor(base.prototype, prop)
if (undefined!==descriptor) Object.defineProperty(Combined.prototype, prop, descriptor)
}
})
})
}
}
// Combine static methods and properties
classes.forEach(base => {
Object.getOwnPropertyNames(base).forEach(prop => {
if (prop !== 'prototype' && prop !== 'name' && prop !== 'length') {
const descriptor = Object.getOwnPropertyDescriptor(base, prop)
if (undefined!==descriptor) Object.defineProperty(Combined, prop, descriptor)
}
})
})
return Combined
}