javascript hoisting for global variable and function

左心房为你撑大大i 提交于 2020-01-16 07:30:20

问题


I was wondering about hoisting. I know if global function name same with global variable, function overwrite variable's name. Is it right?

here is my code.

(function() {
  console.log('console.log#1 ' + globalString); // globalString function 

})();

var globalString = 'I\'m globalString variable';

(function() {
  console.log('console.log#2 ' + globalString); // string
})();

function globalString() {
  console.log('I\'m globalString function');
}

It's result show me like blow

console.log#1 function globalString ()
{
    console.log ( 'I\'m globalString function' );
}

console.log#2 I'm globalString variable

If function definition overwrite variable's console.log#2 print globalString function. I don't know how variable and function hoist. please help.


回答1:


Function declarations (like your globalString()) are hoisted. To the interpreter, your code looks something like this:

var globalString = function globalString() {
  console.log('I\'m globalString function');
};

(function() {
  console.log('console.log#1 ' + globalString); // globalString function 
})();

globalString = 'I\'m globalString variable';

(function() {
  console.log('console.log#2 ' + globalString); // string
})();

Before the initial IIFE runs, globalString is the function. After the initial IIFE runs, but before the second IIFE runs, globalString is then reassigned to the string. Ordinary assignments aren't hoisted - only the variable name is.



来源:https://stackoverflow.com/questions/51255345/javascript-hoisting-for-global-variable-and-function

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