Javascript:new the difference between a function and a direct call function _javascript skill

Source: Internet
Author: User
Copy Code code as follows:

function Test () {
this.name = ' Test ';
return function () {return true;}
}

var test = new Test (); What's the test here?
Is it a Test object? Wrong! Here test is the function () {return true;} that is returned in--test. At this point, the new test () is equivalent to test (), note that it is equivalent to, not equal to, if you use the new test () = = Test () to determine whether the two are equal, you will return false because Javascript compares Object and Function is based on a reference.
To get a clearer picture of the difference between the two, continue with the following code:
Copy Code code as follows:

function Test () {
this.name = ' Test ';
Return ' Test ';
}
var FnT = Test ();
var NewT = new Test ();

Obviously, FnT is the string Test, what about the NewT? Oh, is not the first example of confusion? In fact, at this point NewT is a test object--there is a property named name, whose value is string test.
With the above two pieces of code, we can draw a guess that if the function returns a value of the normal value type (number, String, Boolean), the new function will return an instance object of the function, and if the function returns a reference type (object, Array, Functions), the new function is equivalent to the result generated by the direct call function. This can be confirmed by testing the different types of values returned in the test function.
It's really important to distinguish this point, at least when looking at some object-oriented Framework class library code, there will be less confusion.

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.