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.