Last active
July 9, 2016 16:03
-
-
Save bendc/0000d36ba21dcb91c810 to your computer and use it in GitHub Desktop.
Functional inheritance
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 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?