JavaScript anonymous Functions

Source: Internet
Author: User

You can see this method in some Javascript libraries:

Function () {// code of all databases }();

One purpose of this writing is encapsulation.

JavaScript is not object-oriented, so it does not support encapsulation. However, encapsulation can also be implemented in languages that do not support encapsulation. The implementation method is the anonymous function.

// Define function F (x) {this. x = x; function double (x) {return x * x;} this. getDoubleX = function () {return double (this. x) ;}}// use f = new F (12); alert (f. getDoubleX ());

The above code is very simple. I didn't run it. Anyone who knows about js knows that this is the JS class definition method. Function F is equivalent to a constructor, and other definitions in the function are private external access to the function, such as the double function. In this way, private methods are implemented in disguise. Other members prefixed with "this." are equivalent to public members and can be accessed externally.

The reason why these libraries use a large function to wrap the entire library code is to force users to only access open APIs without exposing internal methods and variables to users. From this point, we can develop the painstaking efforts of these developers.

Simple Form of encapsulation call:

var userName = function() { return "jeff wong" } ();  alert(userName);  

The above code is indeed simple. We can gradually break it down into the following code:

Var anonymousFunc = function () {return "jeff wong"}; // The anonymous function var name = anonymousFunc (); // execute this function to return the name alert (name );

New Function Form (capital Function)

Var a = new Object (); var B = new Function (); // alert (typeof (a); // object // alert (typeof (B )); // function alert (a); // [object Object] alert (B); // anonymous function // alert (a = B ); // false // alert (a = B); // false

As you can see, when we create a new Object, variable a pops up [object Object], and new Function (Note: it is an upper-case Function), and B pops up, an anonymous function is generated. Since B is an anonymous function, the function can certainly be executed. We can continue to try the following code to verify our guess:

Alert (B (); // undefined alert (a (); // The Script Error message "function missing"

A new function has a lower-case function)

Simple empty functions:

Var func = new function () {}; alert (typeof (func); // object alert (func ); // [object Object] // alert (func (); // Script Error func is not a function

In fact, the above Code is equivalent to the following statement:

Function anonymousClass () {}// Anonymous class var instance = new anonymousClass (); alert (typeof (instance); // object alert (instance); // [object Object]

Functions with a return value are not hard to understand.

Var func = new function () {return "jeff wong"}; alert (typeof (func); alert (func); // alert (func ()); // The function is missing due to a script error.

In fact, the above Code is equivalent to the following statement:

Function anonymousClass () {return "jeff wong" ;}// Anonymous class var instance = new anonymousClass (); alert (typeof (instance); // object alert (instance ); // [object Object]

Or the function has a return value, which is slightly different in writing.

Note the following code to distinguish it from (2), because next we will focus on the different forms of writing:

Var func = new function () {return new String ("jeff wong") ;}; alert (typeof (func); // alert (func) expected by the object ); // here ?! // Alert (func (); // The function is missing due to a script error.

The equivalent form of the above Code is still simple:

function anonymousClass() { return new String("jeff wong"); }  var instance = new anonymousClass();  alert(typeof (instance));  alert(instance);  

Have you seen the result after running? That's right. In the third way, when func or instance is popped up, we all unexpectedly get a string "jeff wong ". Carefully compare the code in (2) and (3). Except for the slightly different code in return, the two codes are almost identical. Therefore, we can infer that there is no doubt that, it is the form of new String, which makes our function produce unexpected results. Why?

Originally, in javascript, as long as the constructor after the new expression returns (return) an original type (when there is no return, it is actually the original return type undefined, such as (1 )), for example, if the expression (2) is used, the newly created anonymous Object is returned. If the constructor after the new expression returns a reference Object, such as an Object or function) and Array (Array), the returned reference object will overwrite the new anonymous object. Now let's analyze the Writing Method in (3). Because new String constructs a String reference object, it overwrites the anonymous object created by new, the reference value of the new String is "jeff wong", so the pop-up result must be the value allocated by the current new String.

Finally, let's take a look at the results returned by the following code:

Var func = new function () {var str = new String ("jeff wong"); return str ;}; // rewrite the code // alert (typeof (func )); // In the object expectation, alert (func); // guess what the result is?

Related Article

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.