This is a question about performance and best practice.
Assuming I have a js object that encapsulates a large number of helper methods. The object is being treated as a static class, meaning it is never instantiated and all its methods are basically helper methods.
When using events and jQuery, the object's this scope keeps changing, and since it has a fairly large number of methods I am wondering what is best practice - saving this into _this at the beginning of each method or simply use the object name MyObject.
Over the years I've been doing both, when it comes to singelton/static objects, but I figured there must be just 1 best practice and it's about time to adopt the best approach.
My current research shows that the benefits that come with using _this instead of directly calling MyObject are mainly these two:
_this will always workMyObject every time.Pros of using MyObject:
this apply) MyObject will always workI would like to know if there is a way of globally saving _this (only inside the object's scope of course) and avoid assigning it at the beginning of each method. If not - are there other pros/cons that I am missing or is it considered bad practice to call the object name directly.
This is a simplified object for reference (real object has many more methods).
    var MyObject = {
       init: function() {
         this.registerEvents();
         //other stuff
       },
       registerEvents: function() {
         this.registerOnSomeEvent();
         //registering more events..
         //...
       },
       registerOnSomeEvent: function() {
          var _this = this;
          jQuery('#someid').click(function() {
             _this.doSomething();//option 1
             MyObject.doSomething();//option 2
          });
       },
       doSomething: function() {
         //doing something...
       }
    }
MyObject.init();
Thank you for your help!
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;
})();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With