Home > Web Front-end > JS Tutorial > Detailed explanation of the difference between new function(){} and function(){}()_js object-oriented

Detailed explanation of the difference between new function(){} and function(){}()_js object-oriented

WBOY
Release: 2016-05-16 19:05:37
Original
1249 people have browsed it

Scenario 1:
var yx01 = new function() {return "center of circle"};
alert(yx01);
When we run the scenario 1 code, "[object object]" will be returned and displayed. At this time, the The code is equivalent to:

function anonymous class(){
return "center of circle";
}
var yx01 = new anonymous class();
alert(yx01); us Make the following changes to the code of scenario one:

var yx01 = new function() {return new String("center of the circle")};
alert(yx01);
When we run it, we will find What is returned is the "center of the circle". Why is this?

As long as the constructor after the new expression returns a reference object (array, object, function, etc.), it will overwrite the anonymous object created by new. If it returns a primitive type (without return) In fact, it is return original type undefined), then return the anonymous object created by new
Because new String will construct an object, not a string literal, and if new String(x) takes parameters, then it will be alerted when it is will return x. So yx01 will return the new String("center of the circle") object, and alert yx01 will display the "center of the circle".

Scenario 2:

var yx02 = function() {return "center of circle"}();
alert(yx02); When we run scenario 2 code, the "center of circle" will be displayed. , at this time the code is equivalent to:

var anonymous function = function() {return "center of circle"};
yx02 = anonymous function();
alert(yx02); Obviously, yx02 returns the execution result value of the anonymous function, that is, yx02 is: "center of the circle".

Of course, the execution result of the anonymous function can also be an anonymous object. For specific common applications, please see "A Module Pattern of Javascript"

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