Details about new function () {}and function (){}()

Source: Internet
Author: User

Scenario 1:

VaR yx01 = new function () {return "center"}; alert (yx01 );

We run scenario 1 code and will return"[Object object]", The code is equivalent:

Function Anonymous class () {return "center";} var yx01 = new anonymous class (); alert (yx01 );

The Code of scenario 1 is transformed as follows:

VaR yx01 = new function () {return new string ("center")}; alert (yx01 );

When we run the command, we will find that the returned result is the "Center of the circle". Why?

As long as the constructor after the new expression returns (return) a referenced object (array, object, function, etc.), it will overwrite the anonymous object created by the new expression. If return is returned (return) an original type (undefined is actually the original type of return when no return is required). Then, an anonymous object created by new is returned. (Thank you, lunatic_sun. The description is more accurate)

Because New String constructs an object instead of a string, and if new string (x) carries a parameter, alert returns X. Therefore, yx01 returns the new string ("Circle Center") object, while alert yx01 displays "circle center ".

Scenario 2:

VaR yx02 = function () {return "center"} (); alert (yx02 );

We run the scenario 2 code and will return"Center", The code is equivalent:

VaR anonymous function = function () {return "center"}; yx02 = anonymous function (); alert (yx02 );

Obviously, yx02 returns the execution result value of the anonymous function, that is, yx02 is the center of the circle ".

Of course, the execution result of an anonymous function can also be an anonymous object. For more information about common applications, see JavaScript module mode.

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.