Is there any way to prevent override/overwrite of functions/variables in singleton instance?

前端 未结 3 457
北荒
北荒 2021-02-01 22:19

Consider this pseudo code:

(function(window){
   var options = { /*where everything goes */ };

   var instance = (functio         


        
3条回答
  •  孤独总比滥情好
    2021-02-01 22:58

    What if is_allowed would be completely local?

    (function(window){
       var options = {}, is_allowed;
    
       var instance = (function(options){
         for (var i in options) {
         if (options.hasOwnProperty(i)) {
            this[i] = options[i];
           }
         }
         return this;
       })(options);
    
       instance.callbacks = function(cb){
           /* ... */
       };
    
       function check_allowed(){
         /* check and let this function set [is_allowed] */
       };
    
      window.instance = check_allowed()
                         ? instance
                         : { callbacks: function(){(alert('not allowed'));}  };
    
    } (this) );
    

    jsBin mockup

    BTW: in your code, window.instance would be undefined.

提交回复
热议问题