zoukankan      html  css  js  c++  java
  • new 操作符都做了什么

    解答

    stackoverflow 原提问,https://stackoverflow.com/questions/9468055/what-does-new-in-javascript-do-anyway

    new f(a, b, c)
    

    is eaqal to

    var newInstance = {};
    
    newInstance.__proto__ = f.prototype;
    
    var result = f.call(newInstance, a, b, c);
    
    // If the result is a non-null object, use it, otherwise use the new instance.
    result && typeof result === 'object' ? result : newInstance;
    

    testing

    var f = function () {
        this.test = 1;
    }
    f.prototype.testFn = function () {
        console.log(12);
    }
    
    var newInstance = {};
    
    newInstance.__proto__ = f.prototype;
    
    var result = f.call(newInstance);
    
    // If the result is a non-null object, use it, otherwise use the new instance.
    result && typeof result === 'object' ? result : newInstance;
    
    

    疑问:'1'.toString()为什么可以调用?

    其实在这个语句运行的过程中做了这样几件事情:

    var s = new Object('1');
    s.toString();
    s = null;
    
    • 第一步: 创建Object类实例。注意为什么不是String ? 由于Symbol和BigInt的出现,对它们调用new都会报错,目前ES6规范也不建议用new来创建基本类型的包装类。
    • 第二步: 调用实例方法。
    • 第三步: 执行完方法立即销毁这个实例。

    整个过程体现了基本包装类型的性质,而基本包装类型恰恰属于基本数据类型,包括 Boolean, Number 和 String。

    那为什么 1.toString() 报错?

    > 1.toString()
    VM416:1 Uncaught SyntaxError: Invalid or unexpected token
    

    这是因为 JavaScript 的解释器会把数字后的"."当作小数的点,引发了语法错误。

  • 相关阅读:
    【并查集】亲戚
    【图论】Car的旅行线路 NOIP 2001
    【贪心】排座椅
    【DP】花店橱窗布置
    【NOIP】NOIP考纲总结+NOIP考前经验谈
    【NOIP】考前须知
    NOIP 2016 PJ T4 魔法阵
    NOIP 2016 PJ T3 海港
    【高精度】麦森数 NOIP 2003
    【带权并查集】食物链 NOIP 2001
  • 原文地址:https://www.cnblogs.com/everlose/p/12501285.html
Copyright © 2011-2022 走看看