Douglas Crockford has recently been giving a talk called The Better Parts. The gist of the talk is that JavaScript developers should actually avoid a superset of the The Bad Parts, which now includes new, Object.create, any from of delegation or inheritence, including ES6 classes, and this.
Specifically, Crockford recommends defining new object types by using a constructor function that creates and returns a new object, and that uses closure to create private variables and so on. The obvious issue with this is that every instance has each of its methods bound directly to the instance; there's no delegation, and that's memory hungry. Crockford claims that this is a non-issue, because memory is so cheap. I found that pretty unconvincing.
In a case where some type needed a bunch of methods and a very large number of instances might exist at once, surely any decent JavaScript developer will put those methods in an object, and have every instance delegate to it. Assuming that's true enough, it seems reasonable to just use that kind of simple delegation by default.
A middle ground would be using Object.create to create a new object with a null prototype, binding the methods to that object, then having the Crockford style constructor function give new instances that prototype. This goes against the recommendations in The Better Parts, and as soon as somebody says "why not make that delegation recursive", we're back to where we began.
Obviously, if you are creating a very large number of instances of anything, you'd use delegation as an obvious optimisation, but we're normally talking about relatively small numbers, so for that case, can we just forget the costs?
What are the runtime costs of following Crockford's advice, specifically regarding avoiding delegation? On the kinds of consumer devices that typically run web browsers, are the costs generally minor?
Aucun commentaire:
Enregistrer un commentaire