Skip to content

Instantly share code, notes, and snippets.

@sealocal
Created July 5, 2018 19:16

Revisions

  1. sealocal created this gist Jul 5, 2018.
    59 changes: 59 additions & 0 deletions oop-private-methods.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    'use strict'

    function Car(make, model, year) {
    // public variables
    this.make = make;
    this.model = model;
    this.year = year;
    this.breakPedalIsPressed = false;

    // private variable
    var engineStartAttempts = 0;

    this.startEngine = function() {
    if (checkStartEngineRequirements()) {
    console.log('Engine started!')
    return true;
    } else { // failed requirements
    console.log('Engine start failed!')
    return false
    }
    }

    // public method, accesses public variable
    this.pressBreakPedal = function() {
    this.breakPedalIsPressed = true;
    }

    // public method, accesses public variable
    this.releaseBreakPedal = function() {
    this.breakPedalIsPressed = false;
    }

    // private methods
    var thisCar = this;

    // private method, accesses private variable
    var checkStartEngineRequirements = function() {
    console.log('engineStartAttempts: ', ++engineStartAttempts)
    return ensureBreakPedalIsPressed();
    }

    // private method, accesses public variable
    var ensureBreakPedalIsPressed = function() {
    thisCar.breakPedalIsPressed ? true : console.log('Break pedal is not pressed.')
    return thisCar.breakPedalIsPressed;
    }
    }

    let car = new Car('Tesla', 'Model 4', 2021);

    console.log('\n')

    // start the car with a failed start, then a success start.
    console.log(car.startEngine())
    console.log(car.pressBreakPedal())
    console.log(car.startEngine())
    console.log(car.releaseBreakPedal())

    console.log('\n')