Codog

关注微信公众号:Codog代码狗

0%

实现instanceof和new方法

instanceof

原型链:

image

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的操作:

  1. 创建一个空的简单JavaScript对象(即{});
  2. 为步骤1新创建的对象添加属性proto,将该属性链接至构造函数的原型对象 ;
  3. 将步骤1新创建的对象作为this的上下文 ;
  4. 如果该函数没有返回对象,则返回this。

我们的函数也可以按照这个步骤来:

1
2
3
4
5
6
7
8
9
10
11
12
13
function myNew(Constructor, ...args) {
// 1. 创建空对象
const obj = {};

// 2. 添加原型
obj.__proto__ = Constructor.prototype;

// 3. 调用构造函数,并指定this
const res = Constructor.apply(obj, args);

// 4. 如果构造函数返回为对象则使用之,否则返回本地对象。
return typeof res === 'object' ? res : obj;
}

测试一下:

image

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