[removed] final / immutable global variables?

前端 未结 14 2082
既然无缘
既然无缘 2020-12-13 09:03

I think I know the answer but... is there any way to prevent a global variable from being modified by later-executing

14条回答
  •  鱼传尺愫
    2020-12-13 09:15

    Choose a variable name which is unlikely to be overwritten by accident and trust the programmer to not do stupid things. JavaScript is not Java, so don't pretend it was.

    Also, if what you really want to do is namespacing, use a self-executing function literal:

    var myLibName = (function() {
        var aPrivateVar;
    
        function aPrivateFunction() {}
    
        function accessorForPrivateVar() {
            return aPrivateVar;
        }
    
        // public interface:
        return {
            getPrivateVar : accessorForPrivateVar
        }
    })();
    

提交回复
热议问题