美文网首页
JS中 new 关键字的作用,如何手写一个 new

JS中 new 关键字的作用,如何手写一个 new

作者: WebsnowDrop | 来源:发表于2024-06-27 18:13 被阅读0次
    面试基本上都会考的一道题 js中 new 的作用

    答:

    1. 创建一个对象
    2. 创建对象的原型指向构造函数的 prototype
    3. 将 this = 创建的对象
    4. 执行构造函数
    5. 返回这个对象

    看看 MDN 上 对 new 的描述:new - JavaScript | MDN (mozilla.org)

    1. 创建一个空的简单 JavaScript 对象。为方便起见,我们称之为 newInstance

    2. 如果构造函数的 prototype 属性是一个对象,则将 newInstance 的 [[Prototype]] 指向构造函数的 prototype 属性,否则 newInstance 将保持为一个普通对象,其 [[Prototype]] 为 Object.prototype

      备注: 因此,通过构造函数创建的所有实例都可以访问添加到构造函数 prototype 属性中的属性/对象。

    3. 使用给定参数执行构造函数,并将 newInstance 绑定为 this 的上下文(换句话说,在构造函数中的所有 this 引用都指向 newInstance)。

    4. 如果构造函数返回非原始值,则该返回值成为整个 new 表达式的结果。否则,如果构造函数未返回任何值或返回了一个原始值,则返回 newInstance。(通常构造函数不返回值,但可以选择返回值,以覆盖正常的对象创建过程。)

    手写new

    根据 mdn 的描述手写一个 new

    /**
     *
     * @param FN 构造函数
     * @param args  参数
     */
    function myNew(Fn, ...args) {
      //校验 Fn类型是不是个函数
      if (Fn !== "function") {
        throw new TypeError("Fn 应为函数类型");
      }
      //创建一个空对象newInstance
      var newInstance = {};
      //newInstance的原型指向构造函数的 prototype
      newInstance =
        Fn.prototype instanceof Object
          ? Object.create(newInstance, Fn.prototype)
          : Object.create(Object.prototype);
      // 执行构造函数,并将 this 指向创建的对象newInstance
      var FnRes = Object.apply(newInstance, args);
      // 如果构造函数的返回值为非原始类型,就返回构造函数的返回值,否则,如果构造函数未返回任何值或返回了一个原始值,则返回 newInstance。
      return FnRes instanceof Object ? FnRes : newInstance;
    }
    
    

    相关文章

      网友评论

          本文标题:JS中 new 关键字的作用,如何手写一个 new

          本文链接:https://www.haomeiwen.com/subject/iwuecjtx.html