- 创建一个空的简单JavaScript对象(即
{}
); - 链接该对象(设置该对象的constructor)到另一个对象 ;
- 将步骤1新创建的对象作为
this
的上下文 ; - 如果该函数没有返回对象,则返回
this
。
function myNew() {
const obj = {};
const Constructor = [].shift.call(arguments); // eslint-disable-line
obj.__proto__ = Constructor.prototype; // eslint-disable-line
let ret = Constructor.apply(obj, arguments); // eslint-disable-line
return typeof ret === 'object' ? ret : obj; // eslint-disable-line
}
用法
const TestFn = function(){};
testFn.prototype.name = "我是测试函数";
const testfn = myNew(TestFn);
console.log(testfn);