问题描述
大卫谢里夫进行了一个JS测验,看上去很像-
david sharif made a JS quiz which pretty much looks like-
var foo=1;
function bar(){
return foo;
foo=10;
function foo(){}
var foo =5;
}
typeof bar();//?
据我了解,函数首先被放置,然后在内部声明变量.函数的hosite形式类似于(如果我错了,请纠正我)-
In my understanding, functions are hosited first and then variable declared inside. the hosited form of the function would be something like (correct me if i am wrong)-
var foo=1;
function bar(){
function foo(){}
var foo;
return foo;
foo=10;
foo =5;
}
typeof bar();//?
为什么typeof bar()函数未定义?
why typeof bar() is function not undefined?
这是因为在执行函数时,它会找到第一个foo(它是一个函数)并愉快地返回而无需继续搜索.还是其他?
Is this because of, at the time of function execution, it finds the first foo (which is a function) and returns happily without continuing search. Or something else?
感谢您的时间.
推荐答案
我在 David Shariff 中找到了答案博客.
I found the answer in David Shariff blog.
从他的博客中无耻地复制"-
"Shamelessly copied from his blog"-
即使foo被声明两次,我们也可以从创建阶段就知道在激活对象上创建函数的先于变量,如果属性名称已经存在于激活对象上,那么我们只需绕过声明即可.
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.
因此,首先在激活对象上创建对函数foo()的引用,当我们将解释器获取到var foo时,我们已经看到属性名称foo存在,因此代码不执行任何操作并继续进行.
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
这篇关于Javascript变量和函数吊起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!