Skip to content

Instantly share code, notes, and snippets.

@bendc
Last active July 9, 2016 16:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bendc/0000d36ba21dcb91c810 to your computer and use it in GitHub Desktop.
Save bendc/0000d36ba21dcb91c810 to your computer and use it in GitHub Desktop.
Functional inheritance
function car() {
return {
start: function() {
console.log("Engine on.")
},
accelerate: function() {
console.log("Let's go!")
}
}
}
function roadster(brand) {
var brand = brand
var self = car()
self.setBrand = function(name) {
brand = name
}
self.getBrand = function() {
console.log(brand)
}
return Object.freeze(self)
}
var myCar = roadster("Porsche")
myCar.start() // "Engine on."
myCar.getBrand() // "Porsche"
myCar.setBrand("Jaguar")
myCar.getBrand() // "Jaguar"
@bendc
Copy link
Author

bendc commented Jan 5, 2015

I really like Crockford's "constructor" approach using just functions and closures—there's no new, Object.create, or even this (although using this would be perfectly fine, for example to create a chainable API). You get multiple inheritance, private and public properties and methods, and a lot of other things just by using this simple pattern.

The brand variable illustrates how you can create truly private "properties" for the objects you're creating. You could obviously also use self.brand = brand instead to make the brand property public.

@fvsch
Copy link

fvsch commented Jan 5, 2015

I'm wondering about the memory costs. In your example a car has two methods, a roadster has four methods. If you have a thousand roadsters, that's four thousand methods instead of "just" four methods on 2 prototypes. I'm not knowledgeable enough to know if that's a real problem though.

@maxbeatty
Copy link

I, too, really like this approach and was curious about the memory and performance so I forked to add some tests. You should be able to clone and run the commands in the comment to play with it yourself.

I found that using prototypical inheritance and new was 10x faster and used less memory. For a thousand roadsters, Crockford's new approach used ~387 KB more memory (at 10,000 it used over 2 MB more). I'm not super confident in how I compared memory usage so if you have any feedback, I'd appreciate it.

Do the pro's of "nicer" code outweigh the con's of KB and MB of inefficiencies?

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