Home > Web Front-end > JS Tutorial > body text

JavaScript: Similarities and differences between a new function and calling the function directly

高洛峰
Release: 2016-11-25 14:29:35
Original
972 people have browsed it

Perhaps many people disagree with this. Adding the new keyword before a function means instantiating an object, right? But things are obviously not that simple:


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

var test = new Test(); // here What is test?
 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:

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

var fnT = Test();
var newT = new Test();
Obviously, fnT is the string Test, but 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.

Through 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 the function If a reference type (Object, Array, Function) is returned, 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!