-
-
Save bendc/0000d36ba21dcb91c810 to your computer and use it in GitHub Desktop.
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" |
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.
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?
I really like Crockford's "constructor" approach using just functions and closures—there's no
new
,Object.create
, or eventhis
(although usingthis
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 useself.brand = brand
instead to make thebrand
property public.