Javascript variable and function hoisting

女生的网名这么多〃 提交于 2019-12-01 10:57:46

I found the answer in David Shariff blog.

"Shamelessly copied from his blog"-

Even though foo is declared twice, we know from the creation stage that functions are created on the activation object before variables, and if the property name already exists on the activation object, we simply bypass the declaration.

Therefore, a reference to function foo() is first created on the activation object, and when we get interpreter gets to var foo, we already see the property name foo exists so the code does nothing and proceeds.

If this sound like greek, read the whole blog

The Function Declaration "shadows" the var statement.

Paste this in to your console:

var foo = function(){}
var foo
typeof foo

This is how the code "looks like" to the Interpreter after compiletime:

var bar = function bar(){
  var foo = function foo(){}
  foo
  return foo;
  // never reached
  foo = 10;
  foo = 5;
}
var foo;
foo = 1    
typeof bar();//"function"

Function declarations are evaluated upon entry into the enclosing scope, before any step-by-step code is executed. The function's name (foo) is added to the enclosing scope (technically, the variable object for the execution context the function is defined in).

Example 1

From this example wecan see that even we are declaring foo after the return statement, we can still get foo returned.

function bar() {
  return foo;
  function foo() {} // this will get initialized before the return statement.
}
console.log(typeof bar()); // this will be function

Example 2

From this example we can see that if we are declaring our variables in a normal way after the return statement, they will not execute(assigned).

Declare function after return.

function bar() {
  return foo;
  var foo = function() {} // this will not get assigned
}
console.log(typeof bar()); // this will be undefined

Declare number after return

function bar() {
  return foo;
  var foo = 12; // this will not get assigned
}
console.log(typeof bar()); // this will be undefined

Example 3

Now let's walk through a messier example line-by-line.

function bar() {
  return foo;
  function foo() {}  // <-- initialize foo as a function
  var foo = 11;      // <-- this will not get assigned
}
console.log(typeof bar());  // function

I hope the above example will not only answer you question but also give you a better understanding of:

var foo = function() {} vs function foo() {}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!