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?
Javascript – What would be a better name for Javascript’s “this”
javascriptsyntaxthis
Related Question
- Javascript – JavaScript’s highest integer value that a number can go to without losing precision
- Ruby – What does map(&:name) mean in Ruby
- Javascript – What are the rules for JavaScript’s automatic semicolon insertion (ASI)
- Javascript – the correct way to check for string equality in JavaScript
- Javascript – What does ‘var that = this;’ mean in JavaScript
- Javascript – the explanation for these bizarre JavaScript behaviours mentioned in the ‘Wat’ talk for CodeMash 2012
- Javascript – this JavaScript “require”
Best Solution
this
might be reasonably renamed tocontext
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:
It's important to note there that the value of the
this
object is completely independent of where the containing function is defined.