Working with the JavaScript one of the confusing thing is when using this
var x = {
ele : 'test',
init : function(){
alert(this.ele);
}
}
However when dealing with multiple object and especially events context of this changes and becomes confusing to keep track/understand.
So if anybody has better inputs/guidelines/thoughts/better practices, please share. Also I would like know if using this gives any (performance) advantage or what?
It’s not about performance, it’s about accessing a property of a specific instance of an object:-
Would not display ‘test’ if you hadn’t use
thisin the function.Effectively the above line is the same as:-
the first paramater in the use of
callis assigned tothiswhen the function is executed.Now consider:-
Now you get nothing in the alert. This because the above is effectively:-
In browser hosted Javascript the
windowobject is synonymous with the global object. When a function is called “in the raw” then thethisdefaults to the global object.The classic error is doing something like this:-
However this doesn’t work because the function attached to the onclick event is called by the browser using code like:-
Hence when the function is running
thisisn’t what you think it is.My usual solution to this situation is:-
Note the
elem = nullis IE memory leak work-around.