New functionName of defines a function

  • 2020-03-30 03:04:01
  • OfStack

For example, define two ways to call a function:
 
function getInfo() { 
var info = { 
message: "message" 
}; 
return info; 
} 

Var info1 = getInfo();

Var info2 = new getInfo();

What's the difference between 1 and 2? Does info1 and info2 get the same value?

The first, which is simple and USES a lot, is to execute a function, accept its return value and assign it to an info1 object.

The second condition is generally rare. First of all, the function is also a kind of object, surely you can instantiate objects (object instantiation is called constructors to initialize the object), all the 2nd kind of circumstance is the constructor call getInfo function object, and receive constructor initializes the instance (usually this), and function have a special place is that if the constructor has showed the return value, return will replace this object with the return value. So in case 2, new getInfo calls the constructor (the constructor of the function is the definition itself) and receives the return value info.

Application:

1. For example, HTML defines DOM objects: < Div id = "domId" > < / div> , js code is as follows:
 
function $(domId) { 
var dom = document.getElementById(domId); 
return dom; 
} 

window.onload = function() { 
var dom1 = new $("domId"); 
var dom2 = $("domId"); 
alert(dom1 == dom2); 
} 

The alert prompt displays true. The reason for using $as the name of the function is that it's a bit like jQuery. JQuery USES this style of function definition in its constructors, and the return value is the same whether you call the function with new or directly.

2. Define compatible XMLHttpRequest objects (this example is taken from section 18.1 of the definitive guide to Javascript)
As we all know, different browsers may support asynchronous communication in different ways. Early IE used ActiveX, and the following code defines a compatible XMLHttpRequest object:
 
if (window.XMLHttpRequest === undefined) { 
window.XMLHttpRequest = function() { 
try { 
//If available, use the latest version of the ActiveX object
return new ActiveXObject("Msxml2.XMLHTTP.6.0"); 
} catch (ex1) { 
try { 
return new ActiveXObject("Msxml2.XMLHTTP.3.0"); 
} catch (ex2) { 
throw new Error("XMLHttpRequest is not supported") 
} 
} 
} 
} 

This way, you can define it directly from var XHR = new XMLHttpRequest(), regardless of whether it's Internet explorer or firefox.

Related articles: