Flands
V2EX  ›  问与答

js function 的 toString 调用时机问题

  •  
  •   Flands · Jul 17, 2019 · 2253 views
    This topic created in 2522 days ago, the information mentioned may be changed or developed.
    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 replies    2019-07-17 02:14:30 +08:00
    autoxbc
        1
    autoxbc  
       Jul 17, 2019   ❤️ 1
    这个不是 js 的标准,不同 REPL 的实现结果都不同

    原则上甚至可以以函数对象形式直接输出,没有隐式 toString() 的过程,比如 Firefox 里就没有;
    IE 11 里会打印 'toString' 四次;
    REPL 的实现细节意义不大
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   998 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 22:30 · PVG 06:30 · LAX 15:30 · JFK 18:30
    ♥ Do have faith in what you're doing.