You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var a = 10;
(function (){
console.log(a);
a = 5;
console.log(window.a);
var a = 20;
console.log(a);
})()
输出为
undefined
10
20
我们知道var有变量提升,那请看下面例子
console.log(a); // ReferenceError: a is not defined
a = 3
console.log(a); // undefined
var a = 3
由上可得,只有var会变量提升,没有类型的变量不会提升会报错
所以最开始的例子可以分析如下
var a = 10; // <--------------------|
(function(){ |
var a = undefined; // <--| |
console.log(a); // ------| |
a = 5; |
console.log(window.a); // -----|
a = 20; // <----------|
console.log(a); // ---|
})()
我们稍微变一下题目
var a = 10;
(function(){
var a = undefined;
console.log(a);
a = 5;
console.log(a)
console.log(window.a);
a = 20;
console.log(a);
})()
输出如下
undefined
5
10
20
分析如下
var a = 10; // <--------------------|
(function(){ |
var a = undefined; // <--| |
console.log(a); // ------| |
a = 5; // <-------| |
console.log(a); //--| |
console.log(window.a); // -----|
a = 20; // <----------|
console.log(a); // ---|
})()
题二
var bo = 10;
function foo() {
console.log(bo);
}
(function() {
var bo = 20;
foo();
})();
(function (func) {
var bo = 30;
func();
})(foo)
输出如下
10
10
我们改下代码再看结果
var bo = 10;
function foo() {
console.log(bo);
}
(function() {
var bo = 20;
function foo() {
console.log(bo);
}
foo();
})();
(function (func) {
var bo = 30;
func();
})(foo)
结果如下
20
10
The text was updated successfully, but these errors were encountered:
题一
输出为
我们知道
var
有变量提升,那请看下面例子由上可得,只有
var
会变量提升,没有类型的变量不会提升会报错所以最开始的例子可以分析如下
我们稍微变一下题目
输出如下
分析如下
题二
输出如下
我们改下代码再看结果
结果如下
The text was updated successfully, but these errors were encountered: