Home  >  Article  >  Web Front-end  >  Confusing analysis about javascript function objects_js object-oriented

Confusing analysis about javascript function objects_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:00:19941browse

The function object in js is a fascinating thing, but because it is too flexible, it is often confusing. I will post some code below:

Most people abbreviate it like this:

Copy code The code is as follows:
function test () {}


The entire book "JSVAScript Language Essence" Write like this:
Copy code The code is as follows:
var test = function () {}


The function can be run and assigned immediately:
Copy the code The code is as follows:

var test = function () {} () // test === undefined
var test2 = function () {return 'sugar cake'}() // test2 === 'sugar cake'

But the function abbreviation cannot be run directly. The following code will report an error:
Copy the code The code is as follows:
function test() {}() // SyntaxError: syntax error


If wrapped with the "()" operator, it is normal:
Copy the code The code is as follows:
(function test () {})();


In fact, the function name test has no meaning , remove it and it becomes an anonymous function, which can still automatically execute the code in the function body. Commonly used anonymous function writing methods:
Copy code Code As follows:
(function () {})();


Anonymous functions can also be written like this, which may be more "beautiful":
Copy code The code is as follows:
(function () {}());


See this, new to it Is Brother JS going crazy? I once saw a guy who was working on the C language in my project become petrified immediately after seeing anonymous functions...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn