[英]Hoisting in javascript
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?他说由于 JavaScript 提升,temp 将是未定义的,我不明白为什么它不应该是这样的?
var temp;
temp = setTimeout;
setTimeout = function() {};
so why its undefined?那么为什么它未定义?
This is not the same.这是不一样的。 Your multiple var
declaration also declares setTimeout
:您的多个var
声明还声明了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.用关键字var声明的变量的作用域是它的当前执行上下文。 When a variable is initialized, javascript engine by default initializes the variable to undefined .初始化变量时,javascript 引擎默认将变量初始化为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,在这种情况下,javascript 引擎以以下方式运行代码,
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;从 function(){} 中,假设我们得到 value =10;
now your code seems like:现在你的代码看起来像:
var temp = setTimeout,
setTimeout = 10;
but javascript does the thing in the following way,但是 javascript 以下列方式做这件事,
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 中:什么是javascript提升
scotch: understand hoisting in javascript scotch:理解javascript中的提升
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.