Brendan Eich brendan at mozilla.org
Tue Jul 31 14:34:36 PDT 2007

On Jul 31, 2007, at 12:49 PM, Won wrote:

> Greetings (my first post) --
> I'm pretty excited about the proposed changes coming up for
> ECMAscript. "let" in particular seems overdue. For better or worse, I
> have a C++ programming background, and one of the idioms that I find
> useful every day is RAII (resource acquisition is initialization),
> also called the "Dispose" pattern in other languages. When a variable
> falls out of scope (say, an object that contains a file handle), then
> a method gets called (e.g. close file handle). In particular, RAII
> makes exception-safe coding much more convenient.

You can use try-finally already in ES3 for exception-safe cleanup:

   let (i) {
     try {
       i = getinput();
     } finally {

But RAII means implicit cleanup on block exit, so this is not enough  
-- I just wanted to point it out in case someone on the list new to  
the language missed it.

> In C++, every object gets this treatment. Other languages have special
> syntax/forms, such as "using" in C#, "with" in Python and VB, and
> Ruby/Smalltalk has variables scoped in closure blocks.

The advantage of these approaches is the implicit close or exit  

The only thing on the charts for ES4 that could be used is the  
iterator protocol (wiki export at http://developer.mozilla.org/es4/ 
proposals/iterators_and_generators.html is unfortunately quite out of  
date, and we are moving the dokuwiki to http://ecmascript-lang.org/  
soon -- look there in a week or so):

function raii() {
   try {
     yield getinput();
   } finally {

for (let i in raii()) {

This looks like a loop, which is confusing compared, e.g., to Python  
2.5's with statement. But it has the desired implicit close, if you  
squint hard and consider the generator function with its try-yield/ 
finally the equivalent in explicit declarative overhead to a Python  
object that has the necessary metaprogramming hooks (__enter__,  
__exit__ if memory serves), etc. for C++ (auto storage class instance  
where the class has a dtor that calls cleanup()).

We are now planning to automate close for all iterators, not just for  
generators, when started from a for-in loop, so you could write your  
own object implementing the iteration protocol, and avoid the  
generator function. But the generator function is probably shortest  
and it's built-in.

It wouldn't be hard to sugar this more, but we haven't considered any  
proposals in this area. Feel free to make one.


More information about the Es4-discuss mailing list