Tuesday, March 25, 2014

Apply used to Inherit a Constructor.

function Dog(name, bark){
    this.name = name;
    this.bark = bark;
}

Dog.prototype.speak = function(){
    console.log(this.bark);
}

fido = new Dog('fido','woof');

function Poodle(name, bark){
    Dog.apply(this, [name, bark]);
}
Poodle.prototype = new Dog();
Poodle.prototype.speak = function(){
    Dog.prototype.speak.call(this);
    console.log(this.bark);
}

petrov = new Poodle('Petrov', 'yap');

    The call function in the speak function allows you to call the parent's function and then add extra code to it. Apply works too.

No comments:

Post a Comment