Reputation:
It's recommended to cache globals locally for better performance like so:
function showWindowSize() {
var w = window;
var width = w.innerWidth;
var height = w.innerHeight;
alert("width: " + width + " height: " + height);
}
Is the same true when using the "this" keyword, or is it cached already?
Example:
Game.prototype.runGameLoop = function() {
var self = this;
self.update();
self.draw();
};
Upvotes: 2
Views: 140
Reputation: 413737
The symbol this
is always a local reference, so there's no need to "cache" it for performance reasons. There may be other reasons to preserve its value in another local variable however. When there's a local function that needs access to the this
value from its containing function, then the containing function must make a copy of the value, since this
is always set upon any function invocation.
(It may not be purely accurate to call this
a "local reference"; the point is that the keyword always references a value pertinent to the local function activation record.)
Upvotes: 3