Skip to content

Instantly share code, notes, and snippets.

@SherryH
Last active January 4, 2017 03:31
Show Gist options
  • Save SherryH/46913b98acd9ef741fe8894ccdc7b29f to your computer and use it in GitHub Desktop.
Save SherryH/46913b98acd9ef741fe8894ccdc7b29f to your computer and use it in GitHub Desktop.
Functional and Pseudoclassical classes
//==================================
// 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;
};
var duck = makeAnimal('duck');
duck.speak();
//===================================
// Functional-shared classes (a variation of the Functional class)
// Define methods outside in another object to avoid creating multiple copies of functions through instantiation
var makeAnimalShared = function(name){
var obj = {};
obj.name = name;
var privateVar = 'you cant see me';
obj.speak = AnimalMethods.speak; //Hi I am horse undefined
return obj;
};
var AnimalMethods = {
speak: function(){
//privateVar is not accessible when the method is defined outside object constructing function
console.log('Hi I am', this.name, this.privateVar);
}
};
var horse = makeAnimalShared('horse');
horse.speak();
//====================================
var Animal = function(name){
//var this = Object.create(Animal.prototype); //added by JS compiler when invoked with 'new'
this.name = name;
var privateVar = 'you cant see me';
//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(){
//privateVar is not accessible if it is not associated with the instance through 'this'
console.log('Hi I am', this.name, this.privateVar); //Hi I am dragon undefined
};
// When an instance is created using 'New' keyword, the statements in line 45 and line 48 are automatically added by the compiler
//
var dragon = new Animal('dragon');
dragon.speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment