作者:奥兰度
function myNew(constructor, ...args) {// 非函数if (typeof constructor !== 'function') {throw new Error(`Uncaught TypeError: ${constructor} is not a constructor`)}// 箭头函数if (!constructor.prototype) {throw new Error(`Uncaught TypeError: ${constructor.name} is not a constructor`)}const newObj = Object.create(constructor.prototype)const result = constructor.apply(newObj, args)// 返回值是 objectif (typeof result === 'object' && !!result) {return result}// 返回值不是 objectreturn newObj}
作者:安静
function customNew<T> (constructor: Function, ...args: any[]): T {// 创建空对象继承原型const obj = Object.create(constructor.prototype);// 将 obj 做 this 执行 constructorconst res = constructor.apply(obj, args);// 如果构造函数有返回值,就使用返回值,否则使用 objreturn res ?? obj;}class Foo {name: string;age: number;constructor(name: string, age: number) {this.age = age;this.name = name;}getName() {return this.name;}}const f1 = customNew<Foo>(Foo, '安静', 18);console.log(f1);console.log(f1.getName());
作者:xl
function objectFactory() {let newObject = null;let constructor = Array.prototype.shift.call(arguments);let result = null;// 判断参数是否为函数if (typeof constructor !== "function") {console.log("type error");return;}// 新建一个空对象,对象的原型为构造函数的 prototype 对象newObject = Object.create(constructor.prototype);// 将 this 指向新建对象,并执行函数result = constructor.apply(newObject, arguments);// 判断返回对象let flag = result && (typeof result === "object" || typeof result === "function");// 判断返回结果return flag ? result : newObject;}
作者:寥寥
function myNew(fn, ...args) {if (typeof fn !== 'function') {throw 'fn must be a function'}let obj = new Object();// 将实例对象的__proto__指向构造函数的原型对象obj.__proto__ = Object.create(fn.prototype)// 构造函数的this指向实例对象let res = fn.call(obj, ...args);if (res && (typeof res === 'object' || typeof res === 'function')) {return res;}return obj;}
作者:Leo
function Factory() {this.a = 1}function Factory() {return {b : 3}}function Factory() {this.a = 1; return {a : 3}}const a = new Factory()
作者:
作者:
作者:
作者:
