Home > Web Front-end > JS Tutorial > JavaScript: Analysis of the difference between a new function and calling a function directly_javascript skills

JavaScript: Analysis of the difference between a new function and calling a function directly_javascript skills

WBOY
Release: 2016-05-16 17:29:19
Original
1080 people have browsed it
Copy code The code is as follows:

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

var test = new Test(); // What is the test here?
Is it a Test object? wrong! Here test is a function - function() { return true; } returned in Test. At this time, new Test() is equivalent to Test(). Note that it is equivalent to, not equal to. If you use new Test() == Test() to determine whether the two are equal, false will be returned because Javascript for Object Comparison with Function is based on reference.
In order to more clearly distinguish the difference between the two in the above situation, please continue to look at the following code:
Copy code The code is as follows:

function Test() {
this.name = 'Test';
return 'Test';
}
var fnT = Test();
var newT = new Test();

 Obviously, fnT is the string Test, what about newT? Haha, are you confused by the first example? In fact, newT is a Test object at this time - it has a property named name whose value is the string Test.
From the above two pieces of code, we can make a guess. If the function return value is a value type in the conventional sense (Number, String, Boolean), the new function will return an instance object of the function, and if If the function returns a reference type (Object, Array, Function), the new function will produce the same result as calling the function directly. This can be confirmed by testing by returning different types of values ​​in the Test function.
It is actually quite important to distinguish this point, at least when looking at some object-oriented framework class library code, there will be less confusion.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template