简体   繁体   English

JavaScript和自我执行功能

[英]JavaScript & self executing functions

I'm trying to understand (probably simple concepts) about JS, and I've put together the below piece of code to explain what I don't get. 我试图了解有关JS的(可能是简单的概念),并且我整理了以下代码来解释我不了解的内容。 What I do not understand is where the name variable is stored. 我不明白的是名称变量的存储位置。 Is that variable now global? 该变量现在是全局变量吗?

(function($) {

  var name = '';

  $.helloWorld = function(yourName) {
    name = yourName;
    console.log("Hello " + yourName);
  }

}(jQuery));

The name variable is local to the outer function, because it's declared with the var keyword. name变量是外部函数的局部变量,因为它是使用var关键字声明的。 The inner function is a closure that contains a reference to that variable. 内部函数是一个闭包,其中包含对该变量的引用。 Here's a better example that shows this off: 这是一个更好的例子,可以证明这一点:

(function($) {

  var name = '';

  $.setName = function(newName) {
    name = newName;
  }

  $.showName = function() {
    console.log("Name is: " + name);

}(jQuery));

After defining this, you can do: 定义此之后,您可以执行以下操作:

$.setName("Larry");
$.showName();
$.setName("Fred");
$.showName();

See How do JavaScript closures work? 请参阅JavaScript闭包如何工作?

This should help you understand: 这应该可以帮助您了解:

(function(){

    var name;
    var scope1;

    // Here you can use scope1 and name

    (function(){

        var name;  //  <------------------------
        var scope2;                         // |
                                            // |
        // Here you can use scope1,scope2, and name

        (function(){

            var name;   //  <------------------------------
            var scope3;                                 // |
                                                        // |
            // Here you can use scope1,scope2,scope3, and name

        })();

     })();

})();

// Any\variable declared outside of any function scope is in the global scope.
// A variable declared here can be accessed by window.name from any scope
var name = 5;

So in this snippet, 3 scopes are created by the three functions and in the innermost you can access the variables that have unique names (scope1,scope2, and scope3) as well as the local variable name , which is a separate name from the one it the middle scope. 因此,在此代码段中,这三个函数创建了3个作用域,在最里面,您可以访问具有唯一名称(scope1,scope2和scope3)以及局部变量name的变量,该变量是与该变量不同的名称它是中间范围。 Reusing variable names like that to prevent access to the variable in an outer scope is called shadowing. 像这样重用变量名以防止在外部作用域中访问变量称为影子。

Note that a variable that is not declared with the var keyword is auotmatically assumed to be in the global scope. 请注意,自动假定未使用var关键字声明的变量在全局范围内。 It is a bad practice to declare many variables in the global scope as they can easily conflict with other scripts. 在全局范围内声明许多变量是一个坏习惯,因为它们很容易与其他脚本冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM