Last active
August 29, 2015 13:58
-
-
Save rodolfoag/9965015 to your computer and use it in GitHub Desktop.
This file contains 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
// Javascript Classical Inheritance - Prototypes | |
function Animal (name) { | |
this.name = name; | |
} | |
Animal.prototype.breathe = function () { | |
return "I'm breathing"; | |
}; | |
Animal.prototype.say_name = function () { | |
return this.name; | |
}; | |
function Dog (name) { | |
Animal.call(this, name); | |
} | |
Dog.prototype = Object.create(Animal.prototype); | |
Dog.prototype.bark = function () { | |
return 'ow ow'; | |
}; | |
// Main | |
var toto = new Dog('toto'); | |
console.log(toto.say_name()); | |
console.log(toto.bark()); |
This file contains 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
// Javascript Crockford's Functional Inheritance | |
// spec receives instance properties | |
function animal (spec) { | |
// interface object | |
var that = {}; | |
// Private | |
function breathe () { | |
return "I'm breathing"; | |
} | |
function say_name () { | |
return spec.name || ''; | |
} | |
// Public - goes into that | |
that.breathe = breathe; | |
that.say_name = say_name; | |
return that; | |
} | |
function dog (spec) { | |
var that = animal(spec); | |
// Private | |
function bark () { | |
return 'ow ow'; | |
} | |
// Public | |
that.bark = bark; | |
return that; | |
} | |
// Main | |
var toto = dog({name: 'toto'}); | |
console.log(toto.say_name()); | |
console.log(toto.bark()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment