Why and how to use IIFE in javascript

后端 未结 1 744
有刺的猬
有刺的猬 2020-12-21 23:47

In this example code:

    (function(){
           var obj = function() {

           };

           obj.prototype.hello = function(){
                 consol         


        
1条回答
  •  有刺的猬
    2020-12-22 00:05

    To avoid polluting outer scope. You're sure no variables are going to "get out" of it. But yes, you do need to export it. Either using window.obj = obj; from inside (to make it global) or return it :

    var obj = (function() {
      var obj = function() {};
      obj.prototype.sayHello = function() {}; 
      return obj;
    })();
    

    0 讨论(0)
提交回复
热议问题