0

First example:

function Animal(name) {
    // Instance properties can be set on each instance of the class
    this.name = name;
    this.speak = function() {
        console.log("My name is " + this.name);
    }
}

var animal = new Animal('Petname1');
animal.speak();


function Cat(name) {
    Animal.call(this, name);
}

Cat.prototype = new Animal();

var cat = new Cat('Petname2');
console.log(cat.speak());

Second example:

function Animal(name) {
    // Instance properties can be set on each instance of the class
    this.name = name;
}

Animal.prototype.speak = function() {
    console.log("My name is " + this.name);
};

var animal = new Animal('Petname1');
animal.speak();


function Cat(name) {
    Animal.call(this, name);
}

Cat.prototype = new Animal();

var cat = new Cat('Petname2');
console.log(cat.speak());

In the first example I'm adding directly to class, in the second example I'm adding through prototype. What is the difference? Output is the same.

Wizard
  • 10,985
  • 38
  • 91
  • 165

2 Answers2

2

First of all you have to understand how the new works on Javascript and this link has a good explanation about it.

Based on that, the difference between your two approaches is the quantity of speak functions that is being created while creating new Animals and Cats.

The first approach will have the same instance number of speak function than of Cat and Animal. However the second approach will have only one speak function, no matter how many Cats and Animals you have instantiated. Check out the following snippets.

At this one we can see that 'speak' functions are different for the two Animal instances.

function Animal(name) {
    this.name = name;
    this.speak = function() {
        console.log("My name is " + this.name);
    }
}

var animalA = new Animal();
var animalB = new Animal();

animalA.speak === animalB.speak // false

Assigning to prototype we can see that it is the same for two instances.

function Animal(name) {
    this.name = name;
}

Animal.prototype.speak = function() {
    console.log("My name is " + this.name);
};

var animalA = new Animal();
var animalB = new Animal();

animalA.speak === animalB.speak // true
Community
  • 1
  • 1
Rafael Rocha
  • 756
  • 9
  • 15
0

In the first example speak() is attached to each Animal object created. you can change the behavior of speak() for an object during runtime, it will only be done for that particular object.

However, second example has speak() is defined once and all objects will get updated version if at all it is changed through Animal.prototype.speak assignment.

JsingH
  • 189
  • 7