Last active
December 20, 2015 11:19
-
-
Save singuerinc/6122888 to your computer and use it in GitHub Desktop.
pseudo-classical-pattern
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
function extend(Child, Parent) { | |
Child.prototype = (function () { function F() {}; F.prototype = Parent.prototype; return new F; })(); | |
Child.prototype.constructor = Child; | |
Child.parent = Parent.prototype; | |
return Child.prototype; | |
}; | |
//namespace | |
var world = {species:{animals:{}}}; | |
//Animal pseudo-class | |
world.species.Animal = (function(){ | |
//private | |
var p, running = false; | |
//constructor | |
var Animal = function(name){ | |
this.name = name; | |
}; | |
p = extend(Animal, Object); | |
p.run = function(value){ | |
running = value; | |
console.log('%s is%s running!', this.name, running ? '' : 'n\'t'); | |
}; | |
p.toString = function(){ | |
return this.name; | |
}; | |
return Animal; | |
})(); | |
//Dog pseudo-class | |
world.species.animals.Dog = (function(){ | |
var p; | |
var Dog = function(name){ | |
//pseudo-super() | |
Dog.parent.constructor.apply(this, arguments); | |
}; | |
p = extend(Dog, world.species.Animal); | |
p.sleep = function(){ | |
this.run(false); | |
console.log('%s is sleeping.', this.name); | |
}; | |
return Dog; | |
})(); | |
//new instance | |
var s = new world.species.animals.Dog('Max'); | |
s.run(true); | |
s.sleep(); | |
//output: | |
/** | |
Max is running! | |
Max isn't running! | |
Max is sleeping. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment