Skip to content

Instantly share code, notes, and snippets.

@OmShiv OmShiv/oop-exp.js
Last active Dec 22, 2015

Embed
What would you like to do?
Object Oriented Programming in JavaScript
/*** OOP in JS ***/
// No Classes in JavaScript, but constructor functions.
var a = 5;
// is equivalent to calling
var a = Number(5); // JavaScript abstracts it.
// Number is a Constructor Function
// A Class. First letter caps only for symantics
function Vehicle(type, make) () {
this.type = type;
this.make = make;
}
var car = new Vehicle('four-wheeler', 'Honda');
// The prototype of Vehicle function is copied to car, in car's context
// Hence prototypal inheritance
var car2 = new Vehicle('two-wheeler', 'TVS');
Vehicle.prototpe.candrive = true;
// "prototype" property is available only to functions
// Modifying them would propogate to all instantiated objects, past, present and in future!
car.candrive; // true; prototypal chain is queried from bottom to top
car2.candrive; // true; "true" comes from the prototype
/*** Level 2 Inheritance:
Child Class inheriting from Parent Class ***/
function Vehicle(){
// allocated properties
}
Vehicle.prototype.properties... // Static
Vehicle.prototype.methods ...
function SpaceJet(){
Vehicle.apply(this, args); // args = arguments whatsoever
}
SpaceJet.prototype = new Vehicle();
// prototype is always an object
// here it is going to be copied to all SpaceJets
// Above code inherits properties and methods from Vehicle's prototype.
SpaceJet.prototype.constructor = SpaceJet; // Hardcoding required in JavaScript
// Because only we know its SpaceJet prototype, but for JavaScript,
// ... its just an Object that came from calling Vehicle constructor.
// Overriding
SpaceJet.prototype.candrive = false
// Adding new methods
SpaceJet.prototype.fly = function() {
// ...
}
// Objects
var myJet = new SpaceJet("params");
// Custom property only to this object
myJet.name = 'Chrome Jet';
myJet.fly();
/***
* UPDATE
**/
// Private variables are achieved through IIFE, which are self executing:
var jet = ( function() {
// Private
var wings = 5,
canfly = true;
return {
// Public
getWings: function() {
return wings;
}
// ...
}
}());
jet.getWings();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.