FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

new 的实现原理,动手实现一个 new

Open lgwebdream opened this issue 5 years ago • 3 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

  • 创建一个全新的对象
  • 执行 prototype 链接
  • 绑定到函数调用的this
  • 如果没有返回对象则返回new出来的对象
const myNew = (constructor, ...args) => {
  const obj = {};

  Object.setPrototypeOf(obj, constructor.prototype);

  const result = constructor.call(obj, ...args);

  return result  instanceof Object ? result : obj;
}

gaohan1994 avatar May 03 '24 05:05 gaohan1994

Function.prototype.mynew=function(func,...args) {
        let obj={}
        //新对象 连接 
        obj.__proto__=func.prototype
        let re=func.apply(obj,args)
        return re instanceof Object?re:obj

    
      }
    // 定义一个构造函数
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }

    // 使用 mynew 创建一个新对象
    const john = Person.mynew(Person, 'John', 30);

    console.log(john.name); // 输出: John

Alicca-miao avatar Sep 30 '24 11:09 Alicca-miao