-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2、new.js
33 lines (28 loc) · 1.1 KB
/
2、new.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
function Ctor(){
// ...
}
function myNew (ctor, ...args) {
if (typeof ctor !== 'function') {
throw new Error('myNew function first argument must be a function')
}
let newObj = Object.create(ctor.prototype); //创建一个继承自ctor.prototype的新对象
let ctorReturnResult = ctor.apply(newObj, args); //将构造函数ctor的this绑定到newObj中
let isObject = typeof ctorReturnResult === 'object' && typeof ctorReturnResult !== null;
let isFunction = typeof ctorReturnResult === 'function';
if (isObject || isFunction) {
return ctorReturnResult;
}
return newObj;
}
// let c = myNew(Ctor);
// console.log(c)
// console.log(c.__proto__ === Ctor.prototype);
// console.log(c.__proto__.constructor === Ctor);
// console.log(Ctor.prototype);
// console.log(Ctor.__proto__ === Function.prototype);
// console.log(Ctor.__proto__.constructor === Function);
// console.log(Ctor instanceof Function);
console.log(Function.prototype);
console.log(Function.__proto__);
console.log(Function.__proto__ === Function.prototype);
console.log(Function instanceof Object);