-
Notifications
You must be signed in to change notification settings - Fork 7
/
es5-new-class.js
47 lines (36 loc) · 1 KB
/
es5-new-class.js
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
// * 就不用 TS 了,别折腾自己
// * https://2ality.com/2014/01/new-operator.html
// * ------------------------------------------------ new
const myNew = (clsFn, ...args) => {
const prototypedObj = Object.create(clsFn.prototype);
const constructorResult = clsFn.call(prototypedObj, ...args);
return typeof constructorResult === 'object' && constructorResult !== null
? constructorResult
: prototypedObj;
};
// * ------------------------------------------------ usage
// * Class constructor MyClass cannot be invoked without 'new'
// * deal with it bitch!
// {
// class MyClass {
// constructor(val) {
// this.val = val;
// }
// log() {
// console.log('log', this.val);
// }
// }
// const inst = myNew(MyClass, 233);
// inst.log();
// }
// * --------------------------------
{
function MyClass(val) {
this.val = val;
}
MyClass.prototype.log = function () {
console.log('log', this.val);
};
const inst = myNew(MyClass, 233);
inst.log();
}