Playing with inheretance

by HoffZ

JavaScript

// Parent object
function Car(name, year) {

    // Public vars
    this.name = name;
    this.color = 'No color';
    this.ignitionOn = false;

    // For priv methods to reach this
    var _this = this;
    // You can store vars as private and use getters/setters
    var _year = year;

    // Public funcs
    this.start = function () {
        this.ignitionOn = true;
        console.log('Wroom!');
    };
    this.getYear = function () {
        return _year;
    }

    // Public func that calls a private func    
    this.lightsOn = function () {
        if (_checkEgnition()) {
            console.log('Turning lights on');
        }
    };

    // Special func. It's possible to have a function
    // that has the same name in a child object. See how this
    // func is invoked in child object. 
    // But this looks odd... If you need this type of function:
    // Consider to have a different name in child object
    Car.prototype.specialFunc = function () {
        console.log("I'm special");
    };

    // Private func
    function _checkEgnition() {
        if (_this.ignitionOn) {
            return true;
        } else {
            return false;
        }
    }

}

// You can also create Car functions after the initial definition.
// BUT, then there is no way to call a private function(?). So
// I don't do it this way
Car.prototype.lonelyFunc = function () {
    console.log('So loneley');
}


// Child object
function Mazda(year) {

    console.log('New Mazda created');

    this.productionCountry = 'Japan';

    // Call parent constuctor
    Car.apply(this, ['Mazda', year]);

    // It is possible to call a parent func from a child func
    this.getInfo = function () {
        console.log('Made in ' + this.productionCountry +
            ', ' + this.getYear());
    };

    this.specialFunc = function () {
        Car.prototype.specialFunc();
    }
}

// Inherit car. Using the NEW Object.create function. You
// need the Crockford-hack to suppprt older...