前端面试题 - 121. 模拟new

136 阅读1分钟
const _new = (constructor, ...args) => {
    // 创建对象
    const obj = Object.create(constructor.protorype);
    
    // 执行构造函数
    const result = constructor.apply(obj, args);
    
    // 判断是否合法对象
    return (typeof result !== 'object' || result === null) ? obj : result
}

解释:

  1. const obj = Object.create(constructor.prototype);创建一个空对象obj,并将其原型设置为构造函数的prototype属性。这样,obj就可以继承构造函数原型上的方法和属性。
  2. const result = constructor.apply(obj, args);调用构造函数constructor,并将构造函数的this指向空对象obj。使用apply方法可以将参数列表args传递给构造函数。这一步实际上执行了构造函数的代码,并将构造函数的返回值赋给result变量。
  3. return typeof result === 'object' && result !== null ? result : obj;判断构造函数是否返回了一个对象。如果是对象,则直接返回该对象;否则,返回新创建的空对象obj。这样可以确保在构造函数没有显式地返回对象时,仍然返回一个包含构造函数属性和方法的新对象。