思路:
创建一个空对象,该对象的原型__proto__
指向构造函数的原型对象prototype
,
绑定构造函数的this到该对象(比如bind
,这里使用apply()
函数,因为需要执行一遍构造函数)并执行,
返回该对象,将其引用赋值给等号左侧。
看代码(自己在网页上手打全文,不保证运行通过):
// 构造函数
const Person = (name, age) => {
this.name = name;
this.age = age;
};
// 使用构造函数和_new函数创建实例
const person1 = _new(Person, '张三', 18);
/** 一个简单的new函数 params:
fn: 构造函数
x1: 构造函数参数1 (用剩余参数来接收)
x2: ....
...
**/
function _new (fn, ...args) {
let obj = {};
obj.__proto__ = fn.prototype;
fn.apply(obj, args); // 这里剩余参数args就是类数组,apply比call方便
return obj;
};