I have a JavaScript class:
function Person(n){
// ...
}
Outside of the class, I have the following code:
Person.prototype.shower = function(){ this.dirtFactor=2 }
What does this
in the above code refer to? Does it refer to prototype
, or to the Person
class?
The meaning of this
depends on how you call the function, not how you define it.
Assuming you do something like:
var bob = new Person('whatever n is');
bob.shower();
Then this
will be bob
(which will be an instance of Person
).
Okay, basics first: when you write function Person(o) { ... }
, you are not declaring a class -- JavaScript does not class based, but object based. This statement simply declares a function (which incidentally, are objects as well).
Next, when you create an object like this:
var mellon = new Person('Mellon');
you are creating an object, whose constructor (of sorts) is Person
.
Now, read this carefully: since mellon
's constructor is Person
, all methods in Person
's prototype
will be available in the object.
So if you write:
Person.prototype.shower = function(){ this.dirtFactor=2 }
then the method mellon.shower()
will be available.
I recommend going through Mozilla's intro to OOP in Javascript for some details on this topic.
So to answer your question: this
refers to the object with which the method shower
was invoked. In the above case, it would be mellon
.
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