仿写new

479 阅读1分钟

示例

function Test(name) {
	this.name = name;
}

Test.prototype.sayName = function () {
	console.log(this.name)
}

仿写new

function myNew(constructor, ...args) {
	const obj = {};
    constructor.call(obj, ...args);
	obj.__proto__ = constructor.prototype;

    return obj;
}

输出

const t1 = myNew(Test, 'Eric');

console.log(t1.name); // "Eric"
t1.sayName(); // "Eric"