实现 new
在使用 new 操作符过程中发生的事情
- 创建一个新对象
- 将新对象的原型连接到构造函数的原型上
- 将 this 绑定到这个新对象
- 返回新对象
实现代码
function create(Con, ...args) {
// 创造一个新对象
let obj = {};
// 获取构造函数
// arguments是一个类数组
// let Con = [].shift.call(arguments);
// 将实例对象的隐式原型绑定在构造函数的显式原型上
obj.__proto__ = Con.prototype;
// 将this绑定在实例对象上
let result = Con.apply(obj, args);
return result instanceof Object ? result : obj;
}
// ES6 实现
const create = (Con, ...args) => {
const obj = {};
Object.setPrototypeOf(obj, Con.prototype);
let result = Con.apply(obj, args);
return result instanceof Object ? result : obj;
};
function Foo() {
let a = {
name: "foo",
age: 24,
};
console.log(`---${a.name}---${a.age}---`);
}
const foo = create(Foo);
// ---foo---24---
实现 instanceof
instanceof 原理
instanceof 可以正确的判断对象的类型,内部机制是通过判断对象的原型链中是不是能找到类型的 prototype。
function myInstanceof(left, right) {
// 首先获取类型的原型
let prototype = right.prototype;
// 然后获得对象的原型
left = left.__proto__;
// 然后一直循环判断对象的原型是否等于类型的原型,直到对象原型为 null,因为原型链最终为 null
while (true) {
if (left === null || left === undefined) {
return false;
}
if (left === prototype) {
return true;
}
left = left.__proto__;
}
}
let foo = {
name: "foo",
age: 24,
};
console.log(myInstanceof(foo, Object)); //true
console.log(myInstanceof(foo, Array)); //false