JS的new操作符

57 阅读1分钟
function myNew(constructor, ...args) {
	//创建一个新对象
	const obj = {};
	//将新对象的__proto__指向构造函数的原型对象
	Object.setPrototypeOf(obj, constructor.prototype);
	//传入参数调用构造函数实例化
	const copy = constructor.apply(obj, args);
	//如果构造函数返回一个新对象,直接返回这个对象, 否则返回我们自己创建的对象
	return copy instanceof Object ? copy : obj;
}

function Test(name) {
	this.name = name;
}
const test = myNew(Test, "tom");
console.log(test.name);
console.log(test instanceof Test);

console.dir(test);

关于为什么不通过class来测试

只能用 new 运算符实例化——尝试不使用 new 调用一个类将抛出 TypeError。 --MDN