Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - Is a function hoisted if it is defined within an if condition?

So suppose I have something like this

var x = 1;
   if (function f(){}) {
     x += typeof f;
   }
   x;

This outputs "1undefined". I thought it should have output "1function", because function f(){} should have been hoisted above the if. This is clearly not the case - why? I thought function declarations and bodies were always hoisted to the top of the scope?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Function declarations are hoisted. Function expressions are not.

This creates a named function expression:

if(function f(){})

It doesn't do anything except check to see if the function expression is truthy. (Function expressions are always truthy.)

Regarding named function expressions, see https://kangax.github.io/nfe/#named-expr:

An important detail to remember is that this name is only available in the scope of a newly-defined function

This code is outside the scope of the new function expression, and therefore f is undefined:

x += typeof f;

Within a named function expression, you can refer to its name without a problem:

(function f() {
  alert(typeof f);   //function
})();

alert(typeof f);     //undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...