extend this!

I’ve been working on something fun for the last couple of days (in between patch-revs on other bugs I can’t talk about yet), and I thought I’d blog about it. It’s cool (at least to me) and useful:

John Resig and others involved in the standardization process for the new ECMAScript language proposals have been going back and forth lately over the design of a new language library feature, to facilitate copying properties of one object to another. Object.extend() — essentially you pass an object (the one you mean to extend), and a series of objects (from which you want properties copied), and you get a new object with all the goodness of the others:

From the spidermonkey JS shell:
js> var a = { get x () { print("foo"); return 3 } }
js> var b = [ 1, 2, 3 ]
js> var c = { foo: "bar" }
js> var result = Object.extend({}, a, b, c)
js> result.toSource()
({get x () {print("foo");return 3;}, 0:1, 1:2, 2:3, foo:"bar"})

Notice the getter itself is copied, not the result of its evaluation.

I hope this feature makes it into the standard(s), I think it’s a very powerful, useful, and flexible one. So much so that many of the existing AJAX libraries already have a 5-or-10 line version of it included, under any of a number of names, and with a few variations in semantics. In my opinion, a number of the other features being discussed in lieu of it (like Object.clone) can be implemented trivially in terms of it). A good, consistent semantic for a feature this convenient seems like a great thing for the “library” side of JS, to me. I’d love to land this for 1.9.1, it seems like it would, at least, be handy for extension authors. I hope it survives the committees!

Also, thanks to John for writing a nice test-suite for the feature.

No Comments Yet

You can be the first to comment!

Leave a Comment

  • Comment Policy:Could go here if there's a nagging need Login Instructions: Would go here if there's a desire.