js 函数的 toString 自动调用

toString方法返回一个字符串,其中包含用于定义函数的源文本段
在Function需要转换为字符串时,通常会自动调用函数的 toString 方法
----from: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/toString

function test() {
    
    
    function fn() {
    
    
		console.log('我是fn')
	}
    fn.toString = () => {
    
    
        console.log('toString()')
        return 'toString'
    }
    return fn
}
console.log(test())
//这句代码执行后会打印出
//f return toString

当执行 test() 之后会返回一个 function fn(typeof test()=== function),但是此时会自动调用函数的 toString(),所以返回了 字符串’toString’,如果没有重写 toString() 则会返回函数的字符串形式(返回结果: ƒ fn(){console.log(‘我是fn’)})

猜你喜欢

转载自blog.csdn.net/Chennfengg222/article/details/104745913
今日推荐