Javascript static/singelton - this vs _this vs object name

家住魔仙堡 提交于 2019-12-05 12:08:26

You can encapsulate the entire object in a closure to achieve this without specifiying _this on every function:

window.MyObject = (function () {
    var self = {
        init: function() {

            self.registerEvents();
            //other stuff

        },
        registerEvents: function() {

            self.registerOnSomeEvent();
            //registering more events..
            //...

        },

        registerOnSomeEvent: function() {
            jQuery('#someid').click(function() {
                self.doSomething();//option 1
                self.doSomething();//option 2
            });
        },

        doSomething: function() {
            //doing something...
        }
    };

    self.init();

    return self;
})();

I think your problem is that you go a very long way of painstakingly emulating something you should do instead.

const mySingleton = (function () {
    // Instance stores a reference to the Singleton 
    var instance;
    function init() {
        // Singleton
        // Private methods and variables
        var privateVariable = "Im also private";
        var privateRandomNumber = Math.random();

        return {
            // Public methods and variables
            publicMethod: function () {
                console.log( "The public can see me!" );
            },
            publicProperty: "I am also public",
            get randomNumber() {
                return privateRandomNumber;
            }
         };
         function privateMethod(){
            console.log( "I am private" );
         }

     };
     return {
         // Get the Singleton instance if one exists
         // or create one if it doesn't
         get instance() {
             if ( !instance ) instance = init();
             return instance;
         }
     };   
})();

If you don't want to ever use the this context, never use inheritance and never have more than one instance just don't write those things as methods on an object, but rather declared, private methods in a singleton pattern (which is a revealing module pattern but with only a single instance)

Because as it is you basically make exactly that but you are revealing everything and you spam this hundreds and hundreds of times completely without any purpose. this isn't a constant by design. Don't use it as such.

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