模拟实现object create
function myCreate (obj) {
function F () {}
F.prototype = F;
return new F();
}
模拟实现instanceOf
function myInstanceOf (left, right) {
let _left_prototype = Object.getPrototypeOf(left);
let _right_prototype = right.prototype;
while (_left_prototype) {
if (_left_prototype === _right_prototype) {
return true;
}
_left_prototype = Object.getPrototypeOf(left);
}
return false;
}
模拟实现new
function myNew () {
const _constructor = Array.prototype.shift.call(arguments);
if (typeof _constructor !== 'function') {
console.error('type error!!!');
return
}
const newObj = Object.create(_constructor.prototype);
const result = _constructor.apply(newObj, arguments);
const flag = result && (typeof result === 'object' || typeof result === 'function');
return flag ? result : newObj;
}