instanceof
原型链:

1 2 3 4 5 6 7 8 9 10
| function myInstanceof(a, b) { let p = a; while (p) { if (p === b.prototype) { return true } p = p.__proto__ } return false }
|
测试一下:
1 2 3 4 5 6 7 8
| myInstanceof([], Array) true
myInstanceof([], Object) true
myInstanceof({}, Array) false
|
new
MDN上关于new的操作:
- 创建一个空的简单JavaScript对象(即{});
- 为步骤1新创建的对象添加属性proto,将该属性链接至构造函数的原型对象 ;
- 将步骤1新创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
我们的函数也可以按照这个步骤来:
1 2 3 4 5 6 7 8 9 10 11 12 13
| function myNew(Constructor, ...args) { const obj = {};
obj.__proto__ = Constructor.prototype;
const res = Constructor.apply(obj, args);
return typeof res === 'object' ? res : obj; }
|
测试一下:

参考:https://javascript.plainenglish.io/implement-javascripts-new-operator-yourself-a-killer-frontend-interview-question-68468ad0a227