V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Flands
V2EX  ›  问与答

js function 的 toString 调用时机问题

  •  
  •   Flands · 2019-07-17 00:39:21 +08:00 · 1591 次点击
    这是一个创建于 1739 天前的主题,其中的信息可能已经有所发展或是发生改变。
    function test() {
    
        function fn() {}
    
        fn.toString = () => {
            console.log('toString')
            return 'return toString'
        }
    
        return fn
    }
    
    console.log(test())
    

    输出

    ƒ return toString
    toString // 两次
    

    第一个是因为 fn 将输出为原始类型,所以自动执行 toString,并被console.log(test())打印return值。 此时打印一次toString 但是第二次 toString 什么时候执行的?

    1 条回复    2019-07-17 02:14:30 +08:00
    autoxbc
        1
    autoxbc  
       2019-07-17 02:14:30 +08:00   ❤️ 1
    这个不是 js 的标准,不同 REPL 的实现结果都不同

    原则上甚至可以以函数对象形式直接输出,没有隐式 toString() 的过程,比如 Firefox 里就没有;
    IE 11 里会打印 'toString' 四次;
    REPL 的实现细节意义不大
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2870 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:10 · PVG 16:10 · LAX 01:10 · JFK 04:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.