Last active
August 29, 2015 14:12
-
-
Save csdear/1f67b7d5b35a4cfd3c11 to your computer and use it in GitHub Desktop.
PROTO & MONO - Using PROTOTYPE to establish inheritence in javascript Objects and MONO - Modular Instance Override.
Prototype is used to create base template classes (see Car) and have new instances that inherit those base properties. MONO is spinning off a instance to override its inherited properties/functions and define its own.
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
// 1. the basic javascript object creation | |
function Car(type) { | |
this.speed = 0; | |
this.type = type || "No type"; | |
this.drive = function(newSpeed) { | |
this.speed = newSpeed; | |
} | |
} | |
var bmw =new Car("BMW"); | |
console.log(bmw.speed); // outputs 0 | |
console.log(bmw.type); // outputs "BMW" | |
bmw.drive(80); | |
console.log(bmw.speed); // outputs 80 | |
//2. Prototype used to make "drive" function standard to all functions | |
// drive is used by all, is a standard function | |
function Car(type) { | |
this.speed = 0; | |
this.type = type || "No type"; | |
} | |
Car.prototype = { | |
drive: function(newSpeed) { | |
this.speed = newSpeed; | |
} | |
} | |
var bmw = new Car("BMW"); | |
console.log(bmw.speed); // outputs 0 | |
console.log(bmw.type); //outputs "BMW" | |
bmw.drive(80); | |
console.log(bmw.speed); // outputs 80 | |
//3. MONO to override inherited properties/function from prototype and defining its own custom property/function | |
//Modular properties/functions shared by all thus defining a type… | |
function Car(type) { | |
this.speed = 0; | |
this.type = type || "No type"; | |
} | |
Car.prototype.drive = function(newSpeed) { | |
this.speed = newSpeed; | |
} | |
// A new but common instance… | |
var bmw = new Car("BMW"); | |
// MONO instance -- The honda is faster... | |
var honda = new Car("Honda"); | |
honda.drive = function(newSpeed) { | |
this.speed = newSpeed + 10; | |
} | |
console.log(honda.speed); // outputs 0 | |
console.log(honda.type); // outputs "BMW" | |
honda.drive(80); | |
console.log(honda.speed); // outputs 90 | |
console.log(bmw.speed); // outputs 0 | |
console.log(bmw.type); // outputs "BMW" | |
bmw.drive(80); | |
console.log(bmw.speed); // outputs 80 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment