Skip to content

Instantly share code, notes, and snippets.

@arisetyo
Created November 13, 2012 06:35
Show Gist options
  • Save arisetyo/4064325 to your computer and use it in GitHub Desktop.
Save arisetyo/4064325 to your computer and use it in GitHub Desktop.
Object-Oriented Programming in JavaScript
(function(window) {//catch the window argument
//public variables, outside the constructors
Car.prototype.kpl = 20;//"kilometers per liter"
//a public static property example
Car.music_player = "Kenwood";
function Car(make, model, color) {//the object constructor
/*
this.make = make; // an example of creating public properties inside the constructors
this.model = model;
this.color = color;
*/
//private variables
var _make = make;
var _model = model;
var _color = color;
//public getter method examples
this.getMake = function(){ return _make; };
this.getModel = function(){ return _model; };
this.getColor = function(){ return _color; };
}
//public methods example
Car.prototype.startEngine = function() {
console.log( getDesc(this) + ' engine started');
}
//private method example
function getDesc(context) {
return context.getMake() + ' ' + context.getModel();
}
//make this Car object inside this scope so it is available in the global scope
window.Car = Car;
}(window));//the parentheses make this a self-executing anonymous function that executes automatically
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>OOP JS</title>
<script src="js/Car.js"></script>
<script type="text/javascript">
function init() {
//instantiate the Car object
var car = new Car('Kia','Picanto','Silver');
car.startEngine();
//OTHER EXAMPLES
//console.log(car.getModel() + ' has ' + car.kpl + ' km/liter mileage');
//console.log('this model comes with a ' + Car.music_player + ' music player');
}
</script>
</head>
<body onload="init()">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment