Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

作用域题目汇总 #184

Open
TieMuZhen opened this issue Apr 24, 2022 · 0 comments
Open

作用域题目汇总 #184

TieMuZhen opened this issue Apr 24, 2022 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

题一

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant