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:
- if the object's name changes,
_this
will always work - May be faster (although haven't seen performance testing results) since the browser stays in the same scope and does not need to find out the scope of
MyObject
every time.
Pros of using MyObject
:
- Less code to write.
- Garbage collection management? (less variables to assign)
- May be more readable for some developers (where multiple
this
apply) - Easier to refactor code since
MyObject
will always work
I 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!