Skip to content

Instantly share code, notes, and snippets.

@donburks
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donburks/6e266289fa29735bcad2 to your computer and use it in GitHub Desktop.
Save donburks/6e266289fa29735bcad2 to your computer and use it in GitHub Desktop.
Non-Instance Safe JS
function Cat(colour, size) {
this.colour = colour;
this.size = size;
}
Cat.prototype.meow = function() {
console.log("Meow");
};
function Garfield() {
}
Garfield.prototype = new Cat('orange', 'fat');
var gf = new Garfield();
gf.meow(); //Meow, as expected.
Cat.prototype.swish = function() {
console.log("TAIL SWISH!");
};
gf.swish(); //TAIL SWISH, even though it wasn't part of the original inheritance.
@pr00thmatic
Copy link

pardon me if I interrupt something... but I feel you are as confused as I was, a month ago. It seems like you want Garfield to stop inheriting Cat's functions after creating Garfield "class".

The book "Programming JavaScript Applications" by Eric Elliot (O'reilly), says that object composition is better than class inheritance. Give this a look! https://gist.github.com/VengadoraVG/6673196e840102c7874a

I recommend you that book... it is really good! read the Chapter 3: Objects, by the time you get to "The Flightweight Pattern", I think you'll understand javascript's inheritance better :)

I hope it helps!

@donburks
Copy link
Author

donburks commented Jan 8, 2015

@VengadoraVG: Thanks for the comment, however this particular Gist was used as part of a blog post to demonstrate precisely Elliot's technique. Please see: http://www.donburks.com/mixin-up-your-objects/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment