Javascript new object (function ) vs inline invocation

时光毁灭记忆、已成空白 提交于 2019-12-18 12:35:02

问题


Is there any considerations to determine which is better practice for creating an object with private members?

var object = new function () { 
   var private = "private variable";
   return {
       method : function () { 
           ..dosomething with private;
       }
   }
}

VS

var object = function () {
 ...
}();

Basically what is the difference between using NEW here, and just invoking the function immediately after we define it?


回答1:


The new operator causes the function to be invoked like a Constructor Function.

I've seen that pattern before, but I don't see any benefits of using it.

The purpose of the new operator is to create an object (the this value inside the constructor), setting the right [[Prototype]] internal property, to build the prototype chain and implement inheritance (you can see the details in the [[Construct]] operation).

I would recommend you to stay with the inline invocation pattern.




回答2:


If you're using functions as event handlers you can get memory leaks. Have a look at some of the articles




回答3:


This link provides statistics which also confirms that inline invocation pattern is better.

Please note that the measurement is in operations per second which the higher the better



来源:https://stackoverflow.com/questions/2581565/javascript-new-object-function-vs-inline-invocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!