What is the difference, pros/cons (if any) between these constructs?
new function(obj) {
console.log(obj);
}(extObj);
vs
(function(obj) {
console.log(obj);
})(extObj);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re looking at dealing expressly with an immediately-invoked function, then there isn’t any real difference between the two, except that the first one will return
thisinside the function, to the outside world, automatically (that is whatnewdoes), and by default if a different return value is not specified (regular functions returnundefined).The rest of the major differences are not really going to matter — access to the prototype chain is going to be pointless, having the returned
this.constructorpoint to the anonymous function would give you access to caching the anonymous function for use at a later time (like removing it from an event listener, if you somehow managed to stick the enclosed function in… …that would be a trick in and of itself).Allowing people to cache your immediately-invoked function as a constructor property of the returned
thisobject might be a security-risk… …or it might be really useful… …in very specific scenarios.Every-day purposes of firing code in-line — no real difference.