Home  >  Article  >  Web Front-end  >  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
WBOYOriginal
2016-05-16 17:29:191024browse
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.
Statement:
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