JavaScript OO - Functional Inheritance

by Jennifer Piccione

JavaScript

// Straight from the mouth of Crockford...
// @spec is information about the new instance
// @my is a bundle of shared secrets used by the constructors, but it is optional

var car = function(spec) {
 
    // private variables 
    var that = {}, odometer=0;
    
    // private method
    var increaseOdometer = function(i) {
          odometer+=i;  
    };
    
    var checkOdometer = function() {
         return odometer;   
    }
    
    // privileged methods
    that.getName = function() {
         return spec.name;  
    };    
    
    // we can define a public method by referencing a private method
    // this can make it easier to use the function across the constructor w/out having to include "that."
    that.checkOdometer = checkOdometer;
    that.increaseOdometer = increaseOdometer;
    
    return that;
    
}

var toyota = car({name: "Toyota", year: 1990});
console.log(toyota);

var tesla = car({name: "Model S"});
console.log(tesla, tesla.checkOdometer());
tesla.increaseOdometer(10);
console.log(tesla, tesla.checkOdometer());
console.log(tesla, toyota.checkOdometer());