Why can't you stringify a function expression?

后端 未结 5 1471
醉话见心
醉话见心 2020-12-30 01:06

Why doesn\'t this produce anything?

console.log(JSON.stringify(function(){console.log(\'foobar\');}));
5条回答
  •  长情又很酷
    2020-12-30 01:58

    JSON can't stringify functions at all, it handles them just like undefined or null values. You can check the exact algorithm at EcmaScript 5.1 §15.12.3, see also the description at MDN.

    However you of course can stringify function expression by casting them to a string, try

    console.log("" + function(){console.log('foobar');})
    

提交回复
热议问题