peterschussheim
10/27/2016 - 1:37 PM

10272016

10272016

///This example refactors the previous cell but utilizing JavaScript's prototypal inheritance.

var Car = function(startingSpeed) {
    this.speed = startingSpeed;
}


Car.prototype.stop = function() {
    this.speed = 0;
}

Car.prototype.drive = function() {
    this.speed += 1;
}

var car1 = new Car(20);

car1.drive();

///subclassing
var Prius = function() {
    Car.call(this);
}

Prius.prototype = Object.create(Car.prototype);









Prius.prototype.drive =  function() {
    this.speed += 0.5; ///this will refer to the new keyword
}

var carMethods = {
    drive: function() {
        this.speed += 1;
    }
}
var Car = function() {
    var instance = Object.create(carMethods); ///using Object.create, we take advantage of JavaScript's prototypal inheritence.
    // instance.drive = carMethods.drive; ///just creating a ref,  not taking advantage of prototyping
    instance.speed = 0;
    return instance;
}

var car1 = Car();

10272016

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.