zoukankan      html  css  js  c++  java
  • new实例化背后的逻辑及实现

    模拟new创建实例

    我们经常使用 new 关键字,通过构造函数来创建新实例。那么这个实例化的过程是怎么样的呢?

    1. 创建一个新的空对象 instance

    2. 将 instance 的 proto 属性指向构造函数的原型(Fn.prototype)

    3. 以 instance 来调用执行构造函数(借助 call/apply)

    4. 判断构造函数的返回值,返回 instance 或函数返回值(当构造函数返回值为 object 时)

    下面我们根据上面的步骤来手动实现 new

    function newFn (Fn, params) {
        // 创建一个新的空对象 instance
        const instance = {};
    
        // 将 instance 的 __proto__ 属性指向构造函数的原型(Fn.prototype)
        instance.__proto__ = Fn.prototype;
    
        // 以 instance 来调用执行构造函数(借助 call/apply)
        const result = Fn.apply(instance, params);
    
        // 判断构造函数的返回值,返回 instance 或函数返回值(当构造函数返回值为 object 时)
        return (result && (typeof result === 'object' || typeof result === 'function')) ? result : instance;
    }
    

    只要搞清楚 new 实例化背后的过程,new 实现起来也就比较简单了。


    欢迎来前端学习打卡群一起学习~516913974

  • 相关阅读:
    2440中断
    2440内存管理
    printf不定参数
    时钟体系
    Uart串口
    链接脚本与重定位
    指令速记
    OpenOCD-JTAG调试
    ATPCS规则
    ARM三级流水线
  • 原文地址:https://www.cnblogs.com/formercoding/p/12875856.html
Copyright © 2011-2022 走看看