Created
November 13, 2012 06:35
-
-
Save arisetyo/4064325 to your computer and use it in GitHub Desktop.
Object-Oriented Programming in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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