Skip to content

Instantly share code, notes, and snippets.

@Servuc
Created February 28, 2017 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Servuc/23c611891681917cac0e6de9ce269d17 to your computer and use it in GitHub Desktop.
Save Servuc/23c611891681917cac0e6de9ce269d17 to your computer and use it in GitHub Desktop.
Example of prototype in JS
//Global variable (like static)
App = {
value: 1
};
/*
* Mother class constructor
*/
function ClassA() {
this.value = 1;
}
/*
* Mother class function(s)
*/
ClassA.prototype = {
suchWow: function() {
this.value += 2;
App.value += 4;
}
};
/**
* daughter class
* @param a Imply class inherited (ClassA)
*/
function ClassB(a) {
ClassA.call(this, a);
}
/**
* Some stuff for inheriting
*/
ClassB.prototype = Object.create(ClassA.prototype);
ClassB.prototype.constructor = ClassB;
/**
* Redefine method suchWow of ClassA
*/
ClassB.prototype.suchWow = function() {
this.value += 4;
App.value += 2;
};
// Init one mother, one daughter. See on daughter constructor, "a" parameter is implied ;)
var myA = new ClassA();
var myB = new ClassB();
//Such wow ! Such works ! Such power :D #doge
myA.suchWow();
myB.suchWow();
//Display some informations
console.log( App.value, myA.value, myB.value);
//To execute : npm yourFileName.js
//Install NPM : https://github.com/nodesource/distributions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment