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
function Parent(name, value) {
console.log('parent', name, value);
this.name = name;
this.value = value;
}
Parent.prototype.foo = function () {
console.log(`${this.name}--${this.value}`);
};

function inherit(parentClass, { property }) {
function Child() {
console.log('child', arguments);
parentClass.apply(this, [].slice.call(arguments));
}
// Child.prototype = parentClass.prototype, 避免Parent prototype 更新传递
// Child.prototype = new parentClass() 避免实例化两次parentClass
function tmp(){}
tmp.prototype = parentClass.prototype;
Child.prototype = new tmp();
Child.prototype.constructor = Child; // constructor 指向
for (key in property) {
Child.prototype[key] = property[key];
}

return Child;
}
1
2
3
4
5
6
7
8
const child = inherit(Parent, {
property: {
test() { console.log('test'); },
},
});
const ch = new child('child', 123);
ch.foo();
ch.test();