functionNew(){ let object = {}; letconstructor = [].shift.call(arguments); object.__proto__ = constructor.prototype; let result = constructor.apply(object, arguments); let type = typeof result;
// result是对象并且不是null return (type === 'object' || type === 'function') && result ? result : object; }
1 2 3 4 5 6 7 8
functionNew(F, ...args){ // 指定原型创建对象 let object = Object.create(F.prototype); let result = F.apply(object, args); let type = typeof result;
return result && (type === 'object' || type === 'function') ? result : object; }
1 2 3 4 5 6 7
functionNew(F: () => any, ...args: any): any{ letobject: any = Object.create(fn.prototype); let result: any = F.apply(object, args); lettype: string = typeof result;
return result && (type === 'object' || type === 'function') ? result : object; }
构造器模式检测
在一个函数内部可以使用 new.target 属性来检测是否使用 new 操作符进行了调用,对于使用了 new 关键字,该属性是该函数,否则为 undefined
1 2 3 4 5 6
functionDog(){ console.log(new.target); }
new Dog(); // function Dog(){...} Dog(); // undefined