I asked a question before and somebody give me a guide and I read it and I saw this

  var temp = setTimeout,
  setTimeout = function() {};

He said that temp will be undefined due to JavaScript hoisting and I dont understand why Its not should be like that?

    var temp;
    temp = setTimeout;
    setTimeout = function() {};

so why its undefined?

有帮助吗?

解决方案

This is not the same. Your multiple var declaration also declares setTimeout:

var temp = setTimeout,
    setTimeout = function() {};

which is hoisted to

var temp; // = undefined
var setTimeout; // = undefined
temp = setTimeout;
setTimeout = function() {};

其他提示

The scope of a variable declared with the keyword var is its current execution context. When a variable is initialized, javascript engine by default initializes the variable to undefined. Like,

var a; //it initializes to undefined

Again when you use a variable before declaring them, its now on running context. For Example:

console.log(a);
var a=10;

in this case, javascript engine runs the code in following ways,

var a; // a = undefined
console.log(a); // 
a =10;

it pick up the variable declaration to the top of the execution context but not its value. This is called hoisting that you have already probably known.

In your case:

  var temp = setTimeout,
  setTimeout = function() {};

from function(){}, suppose we get value =10;

now your code seems like:

var temp = setTimeout,
setTimeout = 10;

but javascript does the thing in the following way,

var temp; // temp = undefined
var setTimeout; // setTimeout = undefined
temp = setTimeout; // here temp is undefined as setTimeout is undefined
setTimeout =10;

it keep up all declared variable to the top of stack (Not its value but initializes to undefined).

If you want to learn more, visit the following link:

medium: what is javascript hoisting

scotch: understand hoisting in javascript

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top