function myInstanceof(left, right) {
let proto = Object.getPrototypeOf(left);
let prototype = right.prototype;
while (true) {
if (proto == null) return false;
if (proto === prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
2 手写new操作符
调用new:
创建一个空对象。
将对象的原型设置为构造函数的prototype。
让构造函数的this指向这个对象,执行构造函数的代码,为这个新对象添加属性。
判断函数的返回值类型,如果是值类型,返回创建的对象,如果是引用类型,返回引用类型的对象。
javascript复制代码
function myNew() {
let newObject = null;
let result = null;
let constructor = Array.prototype.shift.call(arguments);
if (typeof constructor !== "function") {
console.error("type error");
return;
}
newObject = Object.create(constructor.prototype);
result = constructor.apply(newObject, arguments);
let flag = result && (typeof result === "object" || typeof result === "function");
return flag ? result : newObject;
}
myNew(构造函数, 初始化参数);