What would be a better name for Javascript's "this"?
javascript, syntax, this
Solution
`this` might be reasonably renamed to `context` in Javascript.
It's really referring to an execution context for the current scope, and while that context can be an instance of a class, it certainly doesn't have to be — it can be any object at all, and it can be modified at run-time.
Proof that there is no guarantee whatsoever that a "method" in Javascript is operating on an instance of the "class" in which it is defined:
function Cat(){
this.texture = 'fluffy';
this.greet = function(){
alert("Pet me, I'm " + this.texture);
}
}
var cat = new Cat();
// Default to using the cat instance as the this pointer
cat.greet(); // Alerts "Pet me, I'm fluffy"
// Manually set the value of the this pointer!
cat.greet.call({texture: 'scaly'}); // Alerts "Pet me, I'm scaly"
It's important to note there that the value of the `this` object is completely independent of where the containing function is defined.
Problem
I'm coming from a Java background, with its class-based inheritance model, trying to get my head around Javascript's prototype-based inheritance model. Part of what is throwing me off, I think is that I have Java's meaning of "this" solidly in mind - and Javascript's "this" is a very different beast. I understand that Javascript's "this" always refers to the function's caller, not the scope in which the function was defined - I mean, I have read that and understand superficially what it means. But I would like to have the understanding more deeply, and I think having another name for it would help. How do you think about JS "this"? Do you make a mental replacement every time you run across it? If so - what word or phrase do you use?