Skip to content

Instantly share code, notes, and snippets.

@rodolfoag
Last active August 29, 2015 13:58
Show Gist options
  • Save rodolfoag/9965015 to your computer and use it in GitHub Desktop.
Save rodolfoag/9965015 to your computer and use it in GitHub Desktop.
// 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());
// 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