A JavaScript function surrounded by parentheses

Source: Internet
Author: User

This code is often seen in JavaScript

function (  $) {        ' body '). css ({' Background-color ': ' #ccc ' }) (jQuery);

One of the JavaScript functions here is enclosed in parentheses, followed by a parenthesis, which is simply not visible in other popular programming languages such as Java, VB, C #, C + +, and PHP. At first glance, this is a novel feature that JavaScript intentionally adds, not really. When we write any program, we always use a feature similar to the code above, but it's just another look. The other is simply the use of parentheses.

In the primary school data is learned the parentheses in the subtraction arithmetic can control the priority level. (+) This is the simplest expression, in the programming language of the logical operation is the case, the first calculation of the parentheses around the (+) part, the result is returned 2, and then multiplied by the subsequent 3, the result is 6, where the parentheses have precedence operation and return the result of the function. Apply this rule to the JavaScript code above

function ($) {     ' body '). css ({' Background-color ': ' #ccc ' })

This code is actually a parenthesis operation, except that the parentheses return is not the result of the calculation in arithmetic, but a function. You can think of this parenthesis operation as a function execution, and the returned result can be a basic type, an object, a function, and so on. There's a second parenthesis here, and the second parenthesis is actually a function call. In most programming languages, the method of calling a function is to add a parenthesis after the function name, and if there are arguments, write the arguments in parentheses, and JavaScript is no exception. So the entire execution of the above example code is the first parenthesis to return a function, the second parenthesis calls the function returned by the first parenthesis, the whole process is actually a function call, but wearing a strange dress is not easy to recognize. The code of the example can actually be replaced by the following code

function EXEC ($) {      ' body '). css ({' Background-color ': ' #ccc ' });}; EXEC (jQuery);

This code is much easier to understand than the previous code, but the results are not the same, but they are different. However, this code is more than a function name, this function is a global function, there is a danger of naming conflicts, which may be more willing to use parentheses to the wording of the reluctant to use this kind of writing reasons. However, there are other ways to replace the use of parentheses, and easier to understand, and there is no problem of global naming conflicts. Here are two alternative ways of writing

void function ($) {    ' body '). css ({' Background-color ': ' #ccc ' });} (jQuery);! function ($) {     ' body '). css ({' Background-color ': ' #ccc ' });} (jQuery);

Of the four example code, three are using anonymous functions, one using the named function, they can be completely substituted between each other, and the same effect, just make the code of the name function is easy to cause naming conflicts.

-------------Split Line-----------------------------------------------------------------------------------------------

It's all about the basic workings of a function enclosed in parentheses, but why choose to do so?  What's the good of doing this? This involves the information hiding mechanism of software engineering. In modern, popular object-oriented programming languages, there are classes of concepts where members of a class have different kinds of access modifiers public, protected, private, but not in JavaScript, but these features can be simulated by function, To achieve a similar effect. In JavaScript, function has the effect of class in other languages. Take the following code as an example

(function() {    varperson = []; functionSetName () {Person.push ("Name:sola Aoi" ); }   functionSetage () {Person.push ("Age:30" ); }   functionSetgender () {Person.push ("Gender:female" ); } window[' Printpersoninfo '] =function() {setName ();        Setgender ();        Setage (); document.write (Person.join ("<br/>" ) ); }}) ();p rintpersoninfo ();

This code plays a very good role in information hiding, in the code there is a variable and four functions, in which the public is a printpersoninfo function, the others are hidden in parentheses in the function inside. So in the outside to write code only need to focus on naming and printpersoninfo function conflict, and do not have to pipe the other three, which is equivalent to the code of person, SetName, Setage, Setgender are private, And only the printpersoninfo is public. Another benefit is that when you change the code, you can modify the person, the SetName, the Setage, the Setgender, without worrying about changing them, because they are restricted to the fixed scope, and are only called in the scope of that piece of code. And it doesn't involve other places. Of course printpersoninfo can not be arbitrarily changed, because it is set to public, in any other unknown place can be called, so can not be arbitrarily changed. This type of writing here has been very obvious, the impact of the changes from five to one, the code of Ease of maintenance greatly improved. The following is a Visual Basic version implementation that achieves the same effect.

ModuleModule1Class PersonPrivate SharedPerson asList ( of String) =NewList ( of String)        Private Shared SubSetName () person. ADD ("Name:sola Aoi")        End Sub        Private Shared Subsetgender () person. ADD ("age:30")        End Sub        Private Shared Subsetage () person. ADD ("Gender:female")        End Sub         Public Shared SubPrintpersoninfo () SetName () Setgender () Setage () Console.Write (String. Join (vbCrLf, person. ToArray ()))End Sub    End Class    SubMain () person.printpersoninfo ()End SubEnd Module

Originally from: http://chhblog.com/article/291.html

A JavaScript function surrounded by parentheses

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.