new
实现一个new
5、6行可以替换,主要是将新生成的obj的原型链接到 需要 new 的对象上
function myNew(constructor, ...args) {
// 1. 创建一个新的空对象
let obj = {};
// 2. 将新对象的原型链接到构造函数的原型
Object.setPrototypeOf(obj, constructor.prototype);
// obj = Object.create(constructor.prototype)
// 3. 将这个新的对象作为 `this` 上下文来执行构造函数
const result = constructor.apply(obj, args);
// 4. 如果构造函数返回的是一个对象类型的值,则返回这个值;否则,返回新创建的对象
return result !== null && (typeof result === 'object' || typeof result === 'function') ? result : obj;
}
// 示例
function Person(name, age) {
this.name = name;
this.age = age;
}
const alice = myNew(Person, 'Alice', 30);
console.log(alice.name); // 输出:'Alice'
console.log(alice.age); // 输出:30
console.log(alice instanceof Person); // 输出:true
Object.create
实现一个Object.create
这里借助了new来创建对象,主要将 传入对象连接到fn的原型链上,然后 new fn即可
function myCreate(obj) {
function fn() {}
fn.prototype = obj;
return new fn();
}
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
},
};
const a = myCreate(person);
a.name = "someone";
a.isHuman = true;
a.printIntroduction();