For example, two calling methods for defining a function:
Copy Code code as follows:
function GetInfo () {
var info = {
Message: ' Message '
};
return info;
}
1, var info1 = GetInfo ();
2, var info2 = new GetInfo ();
What's the difference between 1 and 2? Do Info1 and Info2 get the same value?
The 1th kind is very simple, uses also many, is executes a function, and accepts the function the return value and assigns to the Info1 object;
The 2nd kind of situation is usually very rare. First, a function is also an object, an object can certainly be instantiated (instantiation is actually invoking the object's constructor to initialize the object), and all 2nd is to invoke the constructor of the GetInfo function object and receive the instance of the constructor initialization (typically this). And the function has a special place is that if the constructor has a display return value, it will replace the This object return with the return value. So the 2nd situation new GetInfo is to call the constructor (the function's constructor is its definition itself) and receive the return value info.
Application:
1, such as HTML defines the DOM object: <div id= "Domid" ></DIV>,JS code is as follows:
Copy Code code 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 message displays true. is using $ as a function name because it's a bit like jquery when you use this function? In fact, the function definition of this style is applied in JQuery's constructor, and the value returned is the same whether you call the function new or directly.
2. Define compatible XMLHttpRequest objects (This example is excerpted from section 18.1 of the JavaScript Authority Guide)
We all know that different browsers can support asynchronous communication differently, earlier IE was used in the ActiveX way, the following code defines a compatible XMLHttpRequest object:
Copy Code code as follows:
if (window. XMLHttpRequest = = undefined) {
Window. XMLHttpRequest = function () {
try {
If available, the latest version of the ActiveX object is used
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")
}
}
}
}
In this way, it can be defined directly through the var xhr = new XMLHttpRequest (), without the use of IE or Firefox browser.