我刚刚阅读了一篇关于Ben Cherry的JavaScript范围和提升的精彩文章,其中他给出了以下示例:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,浏览器将发出"1"警报.
我仍然不确定它为什么会返回"1".他说的一些事情就像是:所有的功能声明都被提升到顶部.您可以使用函数来调整变量的范围.仍然没有为我点击.
请考虑以下Javascript代码.
function correct()
{
return 15;
}
function wrong()
{
return
15;
}
console.log("correct() called : "+correct());
console.log("wrong() called : "+wrong());Run Code Online (Sandbox Code Playgroud)
correct()上面代码片段中的方法返回正确的值,在这种情况下为15.15然而,该方法返回wrong().大多数其他语言并非如此.
但是,以下函数是正确的,并返回正确的值.
function wrong()
{
return(
15);
}
Run Code Online (Sandbox Code Playgroud)
如果语法错误,它应该发出一些编译器错误,但它不会.为什么会这样?
我只想试着理解这个函数表达式.
似乎如果我创建一个p似乎包含函数声明的函数expression(),函数声明a()将返回undefined.
var p;
p = function a() { return 'Hello' }
typeof p; // returns 'function'
typeof a; // returns 'undefined'
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么会这样吗?
如果我的术语也关闭了,请告诉我.
我在这里对可变提升概念有点困惑。为什么第一个console.log(flag)输出undefined?它不应该捕获已经初始化的 false 值在作用域链中向上移动吗?
var flag = false;
(function(){
console.log(flag);
var flag = true; // JavaScript only hoists declarations, not initialisations
console.log(flag);
if(flag){
let name = "John";
const age = "24";
console.log(name);
console.log(age);
}
//console.log(name); //ReferenceError: name is not defined ( as name is block scoped here )
//console.log(age); //ReferenceError: age is not defined ( as age is block scoped )
})();Run Code Online (Sandbox Code Playgroud)