你如何用JavaScript解释这种结构?[英] How do you explain this structure in JavaScript?

本文是小编为大家收集整理的关于你如何用JavaScript解释这种结构?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

(function() 
 {
     //codehere
 }
)();

这种语法有什么特别之处? 什么是()();暗示?

推荐答案

创建一个匿名函数,闭合和全部,最终()告诉它执行自身.

基本上与:

function name (){...}
name();

因此,基本上,此代码没有什么特别的,它只是创建方法并调用它而无需命名的"快捷方式".

这也意味着该函数是一个关闭的功能,或者是对象上的内部函数,并且当您需要闭合功能时最有用.

其他推荐答案

这是一个匿名函数.

目的是创建一个新的范围,局部变量不会流血.例如:

var test = 1;
(function() {
  var test = 2;
})();
test == 1 // true

关于此语法的一个重要说明是,如果您还没有,您应该养成用半彩色终止陈述的习惯.这是因为JavaScript允许在调用函数名称及其括号之间的行馈电.

下面的摘要将导致错误:

var aVariable = 1
var myVariable = aVariable

(function() {/*...*/})()

这是实际在做的:

var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();

创建新块范围的另一种方法是使用以下语法:

new function() {/*...*/}

区别在于,以前的技术不会影响关键字" this"指向的位置,而第二个则不会影响

.

JavaScript 1.8还具有完成同一件事的Let语句,但不用说,大多数浏览器不支持它.

其他推荐答案

这是一个自我执行的匿名函数.末尾的()实际上是在调用函数.

一本好书(我已经读过),解释了JavaScript中这些类型的语法用法是面向对象的javascript .

本文地址:https://www.itbaoku.cn/post/627630.html

问题描述

(function() 
 {
     //codehere
 }
)();

What is special about this kind of syntax? What does ()(); imply?

推荐答案

The creates an anonymous function, closure and all, and the final () tells it to execute itself.

It is basically the same as:

function name (){...}
name();

So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.

This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.

其他推荐答案

It's an anonymous function being called.

The purpose of that is to create a new scope from which local variables don't bleed out. For example:

var test = 1;
(function() {
  var test = 2;
})();
test == 1 // true

One important note about this syntax is that you should get into the habit of terminating statements with a semi-colon, if you don't already. This is because Javascript allows line feeds between a function name and its parentheses when you call it.

The snippet below will cause an error:

var aVariable = 1
var myVariable = aVariable

(function() {/*...*/})()

Here's what it's actually doing:

var aVariable = 1;
var myVariable = aVariable(function() {/*...*/})
myVariable();

Another way of creating a new block scope is to use the following syntax:

new function() {/*...*/}

The difference is that the former technique does not affect where the keyword "this" points to, whereas the second does.

Javascript 1.8 also has a let statement that accomplishes the same thing, but needless to say, it's not supported by most browsers.

其他推荐答案

That is a self executing anonymous function. The () at the end is actually calling the function.

A good book (I have read) that explains some usages of these types of syntax in Javascript is Object Oriented Javascript.