Last active
April 22, 2016 10:21
-
-
Save batsify/aae7cc09832b7e2914c1e48e081c6acf to your computer and use it in GitHub Desktop.
How use super like in OOP with a Prototypal Language
This file contains hidden or 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
// How use super like in OOP with a Prototypal Language : | |
!function(){ | |
'use strict'; | |
console.log("Starting"); | |
var Feline = function(name, race) { | |
if ( !(this instanceof Feline) ) return; | |
this.name = name; | |
this.race = race || "Feline" | |
console.log("Feline DNA new say : A new " + this.race + " is born : " + this.name); | |
}; | |
Feline.prototype.hello = function(){ | |
console.log("Feline DNA hello say : " + this.myName()); | |
}; | |
Feline.prototype.myName = function(){ | |
return "My name is " + this.name; | |
} | |
console.log(Feline); | |
console.log('--- Here: leo = new Feline("Léo");'); | |
var leo = new Feline("Léo"); | |
console.log(leo); | |
console.log('--- Here: leo.hello();'); | |
leo.hello(); | |
var Cat = function(_super) { | |
return function(name, owner) { | |
if ( !(this instanceof Cat) ) return; | |
_super.apply(this, [name, "Cat"]); | |
this.owner = owner; | |
}; | |
}(Feline); | |
Cat.prototype = Object.create(Feline.prototype); | |
Cat.prototype.constructor = Cat; | |
Cat.prototype.hello = function(_super){ | |
return function(){ | |
_super.apply(this); | |
console.log("Cat DNA hello say: And my owner is " + this.owner); | |
console.log("Cat DNA hello say: ... Yes, I inherit also of this capacity to say " + this.myName()); // Method exists only in Feline prototype | |
}; | |
}(Cat.prototype.hello); // Stick to the initial hello method through the prototype chain | |
console.log(Cat); | |
console.log('--- Here: kitty = new Cat("Kitty", "John");'); | |
var kitty = new Cat("Kitty", "John"); | |
console.log(kitty); | |
console.log('--- Here: kitty.hello();'); | |
kitty.hello(); | |
console.log("End."); | |
}(); | |
/* | |
Starting | |
function Feline() | |
--- Here: leo = new Feline("Léo"); | |
Feline DNA new say : A new Feline is born : Léo | |
Object { name: "Léo", race: "Feline" } | |
--- Here: leo.hello(); | |
Feline DNA hello say : My name is Léo | |
function Cat() | |
--- Here: kitty = new Cat("Kitty", "John"); | |
Feline DNA new say : A new Cat is born : Kitty | |
Object { name: "Kitty", race: "Cat", owner: "John" } | |
--- Here: kitty.hello(); | |
Feline DNA hello say : My name is Kitty | |
Cat DNA hello say: And my owner is John | |
Cat DNA hello say: ... Yes, I inherit also of this capacity to say My name is Kitty | |
End. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment