Take this code:
var obj = {
init: function(){
console.log(obj.count);
//or
console.log(this.count);
},
count: 1,
msg: 'hello'
}
obj.init();
I can access property of obj by this or the variable name obj both. Is there any advantage in using this ? Because in my opinion using the object name obj adds clarity to the code.
The advantage of
thisis that it allows the same function to work for multiple instances of that type of object. The corresponding disadvantage of using the variable nameobjis that it only refers to that specific instance.In your case you’ve only got a singleton object since you assign your
objvariable to an object literal, so there won’t ever be multiple instances, but still if you later copied that code to create another similar object with a different variable name for that new object you’d have to find/replace all the uses ofobjand change them to the new variable name.Note that in JavaScript the value of
thiswithin a function depends on how the function was called, not whether the function was defined as a property/method of an object. See https://developer.mozilla.org/en/JavaScript/Reference/Operators/this.As far as making the code readable,
thisis a standard part of the language that all experienced JS coders are (or should be) familiar with, and in my opinion it is more readable because you don’t have to look back to see whereobjwas declared…