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?
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
Implicit Binding is applied when you invoke a function in an Object using the dot notation. this in such scenarios will point to the object using which the function was invoked. Or simply the object on the left side of the dot.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With