Skip to content

Instantly share code, notes, and snippets.

@SherryH
Last active May 6, 2018 10:21
Show Gist options
  • Save SherryH/f37e670b7771820f73ab0a7a0ae3d9f3 to your computer and use it in GitHub Desktop.
Save SherryH/f37e670b7771820f73ab0a7a0ae3d9f3 to your computer and use it in GitHub Desktop.
Functional and Pseudoclassical subclasses
//==================================
// Functional classes
// Define methods inside the object constructing function
var makeAnimal = function(name){
var obj = {};
obj.name = name;
var privateVar = ' you can see me';
obj.speak = function () {
//privateVar is accessible through closure
console.log('Hi I am '+ obj.name+ privateVar); //Hi I am duck you can see me
};
return obj;
};
// A functional subclass
var makeWalkingAnimal = function(name, legNum) {
var obj = makeAnimal(name); //calling the superclass
obj.legNum = legNum;
var oldSpeak = obj.speak;
obj.speak = function (age) {
if (age < 2){
oldSpeak();
} else {
console.log('Hi I am '+ obj.name+ ' I have '+obj.legNum+' legs');
}
};
return obj;
};
var kiwi = makeWalkingAnimal('Gugu',2);
kiwi.speak(1); //"Hi I am Gugu you can see me"
kiwi.speak(2); //"Hi I am Gugu I have 2 legs"
//============= Pseudoclassical Classes =======================
var Animal = function(name){
//var this = Object.create(Animal.prototype); //added by JS compiler when invoked with 'new'
this.name = name;
//return this; //added by JS compiler when invoked with 'new'
};
// All the JS functions by default have the prototype property for aggregating methods
Animal.prototype.speak = function(){
console.log('Hi I am', this.name); //Hi I am Butter
};
// A functional subclass
var FlyingAnimal = function(name) {
//var this = Object.create(FlyingAnimal.prototype); //added by JS compiler when invoked with 'new'
//we dont want to invoke Animal() with 'new' keyword
//we still want the property assignment from superclass
Animal.call(this, name);
//return this;
};
//establish the prototypal chains so that failed method lookups gets delegated
FlyingAnimal.prototype = Object.create(Animal.prototype);
FlyingAnimal.prototype.speak = function (age) {
if (age < 2){
Animal.prototype.speak.call(this);
} else {
console.log('Hi I am '+ this.name+ ' I can fly');
}
};
FlyingAnimal.prototype.constructor = FlyingAnimal;
var butterfly = new FlyingAnimal('Buttter',2);
butterfly.speak(1); //"Hi I am Buttter"
butterfly.speak(2); //"Hi I am Buttter I can fly"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment