What does it mean?

I have a JavaScript class:

function Person(n){ // ... } 

Outside the class, I have the following code:

 Person.prototype.shower = function(){ this.dirtFactor=2 } 

What does this mean in the above code? prototype this apply to prototype or to the Person class?

+6
javascript
source share
5 answers

Well, the basics first: when you write function Person(o) { ... } , you are not declaring a class - JavaScript is not based on a class, but based on an object. This operator simply declares a function (which, incidentally, is also an object).

Next, when you create such an object:

 var mellon = new Person('Mellon'); 

you create an object whose constructor (of its kind) is Person .

Now read this carefully: since the constructor is a mellon Person , all objects in the Person prototype will be available in the object.

So if you write:

 Person.prototype.shower = function(){ this.dirtFactor=2 } 

then the mellon.shower() method will be available.

I recommend reading Mozilla's introduction to OOP in Javascript for more information on this topic.


So, to answer your question: this refers to the object with which the shower method was called. In the above case it will be mellon .

+1
source share

The meaning of this depends on how you call the function, and not how you define it.

Assuming you are doing something like:

 var bob = new Person('whatever n is'); bob.shower(); 

Then this will be bob (which will be an instance of Person ).

+4
source share

This refers to a human instance.

So, when you do 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 report the value of the field to which the function is assigned

+1
source share

It refers to an instance of the Person class

  var instance = new Person (...);

    instance.shower ();  // Here will be this.dirtFactor assigned to instance.dirtFactor
+1
source share

This refers to the object on which the shower is being called. In particular, you will eventually do

  p = new Person(n); 

This will execute the Person function and create a new empty object that will be available as this in the constructor. This object will then be provided with a reference to Person.prototype , and any attribute references that do not work with p will be displayed on Person.prototype to see if it is found there.

If he called p using p.shower() , then this will return to p . The thing is, there are no instances and classes in javascript. Person.prototype is a single object, and all objects created by Person will have 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 you called the method on.

+1
source share

All Articles