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

27. 什么是闭包 #44

Open
webVueBlog opened this issue Jun 6, 2022 · 0 comments
Open

27. 什么是闭包 #44

webVueBlog opened this issue Jun 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

闭包是函数和声明该函数的词法环境的组合。即,它是一个内部函数,可以访问外部或封闭函数的变量。闭包具有三个作用域链

自己的范围,其中在其大括号之间定义的变量

外部函数的变量

全局变量

让我们以闭包概念为例,

function Welcome(name) {
  var greetingInfo = function (message) {
    console.log(message + " " + name);
  };
  return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John

根据上面的代码,即使在外部函数返回之后,内部函数(即 greetingInfo)也可以访问外部函数作用域(即 Welcome)中的变量。

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