Raskolnikov
Raskolnikov

Reputation: 3999

How prototype works in javascript?

I know that there is question already, but I have to make this clear.

function Animal(species) {
    this.species = species;
}
Animal.prototype.getSpecies = function() {
    return "Animal is " + this.species;
};


(function() {
    var animal1 = new Animal("Snake");
    var animal2 = new Animal("Wolf");
    var animal3 = new Animal("Tiger");
}());

And this is how I understand. enter image description here

Function/Method getSpecies() is shared between all Animal objects in prototype object. Did I understand correctly?

Is it correct to say that _Proto_ is pointer to prototype object ?

Thanks for help.

Upvotes: 2

Views: 231

Answers (2)

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

Yes you right If you use animal1.getSpecies == animal2.getSpecies true

anima2.getSpecies == animal3.getSpecies true

Only one copy of function and prototype exists

Upvotes: 0

philipp
philipp

Reputation: 16485

Yes you are right, that is how it works! But __proto__ is not a pointer, it is a reference and its use is depricated. In Javascript real pointers do not exist, but references do.

If you create a Type that inherits from Animal like this:

function FastAnimal () {
    Animal.call(this, 'extreme-fast');
}

FastAnimal.prototype = Object.create(Animal.prototype);
FastAnimal.prototype.constructor = FastAnimal;
FastAnimal.prototype.getSpeed = function () { return '1MILLION'; };


var fa = new FastAnimal();


fa.getName = function () {}

Than a lookup for a property or Method in fa will go that way:

  1. does fa has this OWN Property (as getName)
  2. does it exist in FastAnimal.prototype (getSpeed)
  3. does it exist in Animal

In general: This lookup goes on as long as there are prototypes on the way. However, that is what happens under the hood and called the prototype chain.

N.B.:

If you would like to loop over the properties of a given Object, there are two ways:

for (var prop in obj) {
    //do stuff
}

That includes properties of the prototype and normally not what people want, that's why

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        //do stuff
    }
}

is a common pattern, BUT there is a new type of loop coming up and hopefully usable in the near future.

for (var prop of obj) {}

This one also explicitly excludes properties of the object’s prototype.

Upvotes: 6

Related Questions