简体   繁体   English

此自执行匿名函数和此正常函数调用之间有什么区别?

[英]What's the difference between this self-executing anonymous function and this normal function call?

What's the difference between this: 这有什么区别:

(function() {
    var Person = {
        sayHello: function() {
            alert('Hello World');
        }
    }

    Person.sayHello();
})();

And this: 和这个:

var Person = {
    sayHello: function() {
        alert('Hello World');
    }
}

Person.sayHello();

Besides the latter creating a public function and the former being a way to create a kind of private function (you cannot reference Person outside of the parenthesis... what's the difference? 除了后者创建公共功能,而前者是创建一种私有功能的方式(您不能在括号之外引用Person……有什么区别?

The first one doesn't leave a variable called Person floating around the current scope (because there are no references to it left when the IIFE finishes executing), nor does it overwrite any other variables called Person in that scope. 第一个不会使名为Person的变量在当前范围内浮动(因为IIFE完成执行时将没有对它的引用),也不会覆盖该范围内的任何其他变量Person

(The second one is missing a } but I assume that is a typo in the question). (第二个缺少}但我认为这是问题中的错字)。

The first one has the Person variable private. 第一个具有Person变量private。 Once executed, it discards everything inside the SE Function. 一旦执行,它将丢弃SE函数中的所有内容。

the 1st version creates 'isolated namespace', so if you have the Person variable somewhere in your code, then it won't be overwritten 第一个版本会创建“隔离的名称空间”,因此,如果您的代码中有Person变量,则不会被覆盖

The 2nd version creates Person in global scope, so in can lead to conflicts with another parts of your code 第二个版本在全局范围内创建Person,因此in可能导致与代码其他部分的冲突

more info 更多信息

The first one is a Self-Executing Anonymous Function , which means that nothing defined in there is accessible outside of it and when it executes, everything inside it is "lost" . 第一个是自执行匿名函数 ,这意味着其中定义的任何内容都无法从其外部访问,并且当其执行时,其内部的所有内容都会“丢失”

To be able to call the sayHello() method outside that function you have to expose the object Person to the global 'window' object : 为了能够在该函数之外调用sayHello()方法,您必须将对象Person公开给全局“ window”对象

//Assign 'Person' to the global variable 'Person'
window.Person = Person;

The second one is variable containing an object and since that variable is declared in the global scope, it is accessible from everywhere and new methods and properties as well as instances of the object can be created. 第二个变量是包含对象的变量,并且由于该变量是在全局范围内声明的,因此可以在任何地方访问它,并且可以创建新的方法和属性以及对象的实例。

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

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