The toString of the js function is automatically called

The toString method returns a string containing the source text segment used to define the function.
When a Function needs to be converted to a string, the toString method of the function is usually called automatically
----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

When test() is executed, it will return a function fn(typeof test()=== function), but at this time, the toString() of the function will be automatically called, so the string'toString' is returned. If toString() is not rewritten It will return the string form of the function (return result: ƒ fn()(console.log('I am fn')))

Guess you like

Origin blog.csdn.net/Chennfengg222/article/details/104745913