Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript new keyword - Returning new object created inside inner anonymous function
    primarykey
    data
    text
    <p>I'm going through a book on DOM scripting and the following function appears within the book when they talk about Ajax.</p> <pre><code>function getHTTPObject() { if(typeof XMLHTTPRequest == "undefined") XMLHTTPRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0");} catch(e) {} //several more fall through try/catch blocks attempting //to create different XMLHTTP objects. //If none succeed... return false; } return new XMLHTTPRequest(); } </code></pre> <p>If the new keyword is used within the try/catch block when attempting to create the ActiveXObject within the inner anonymous function that is assigned to XMLHTTPRequest, why is the new keyword used again when returning the result of XMLHTTPRequest at the end of getHTTPObject()?</p> <p>It seems like it's returning a new, new object.</p> <p><strong>Edit</strong></p> <p>I understand broadly what the purpose of the code is, to check if the XMLHTTPRequest constructor exists, and if not define one that tries to make XMLHTTP ActiveXObjects. I'm with you this far.</p> <p>Supposing XMLHTTPRequest is undefined.</p> <p>XMLHTTPRequest is assigned the inner function constructor.</p> <p>Then at the bottom of getHTTPRequest XMLHTTPRequest is called. </p> <p>Within XMLHTTPRequest, a new ActiveXObject is created and returned to the caller, in this case getHTTPObject. Now getHTTPObject in turn returns this object out to it's caller. But again, why does the line:</p> <pre><code>return new XMLHTTPRequest() </code></pre> <p>need that new there if the new (i.e. object instantiation) already occurs within the code of that try block inside of the defintion / scope of XMLHTTPRequest()? Why not simply:</p> <pre><code>return XMLHTTPRequest() </code></pre> <p>Thanks everyone for the answers. It's very possible, likely even, that I just don't have a strong enough grasp of JS constructor syntax and that's what's tripping me up here.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload