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();
};
The symbol
thisis 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 thethisvalue from its containing function, then the containing function must make a copy of the value, sincethisis always set upon any function invocation.(It may not be purely accurate to call
thisa “local reference”; the point is that the keyword always references a value pertinent to the local function activation record.)