What does `this` refer to?
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 t开发者_如何学Pythono? 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
.
It refers to the instance of the person
So when you do a
var Mike = new Person();
then this is Mike
Example
<input type="text" id="field" value="Bla" />
<script>
document.getElementById('field').onfocus=function() {
alert(this.value)
}
</script>
will alert the value of the field the function is assigned to
It reffers to a instance of Person class
var instance = new Person( ... ); instance.shower(); // Here will be this.dirtFactor assigned to instance.dirtFactor
This refers to the object upon which shower
is called. Specifically, you will eventually end up doing
p = new Person(n);
This will execute the Person
function and create a new, empty object which will be accessible as this
in the constructor. That object will then be given a link to Person.prototype
and any attribute references that fail on p
will look on Person.prototype
to see if it's found there.
If it's called on p
, using p.shower()
, then this
will return to p
. The point is though that there aren't instances and classes in javascript. Person.prototype
is one object and all objects that are constructed by Person
will share a reference to it.
Removing prototypes all together, you can just do
person = {'shower': function () {
this.dirtFactor = 2; }
}
person.shower();
console.log(person.dirtFactor);
and you will see that this
still refers to the object upon which you called the method.
精彩评论