Hacker News new | ask | show | jobs
by trealira 936 days ago
I think it also makes sense in Python, where it can be used to automatically close a file, or

  with open(filename) as my_file:
      data = my_file.read()
Or with acquiring and releasing a lock:

  lock = threading.Lock()
  with lock:
      pass # do stuff

That being said, I prefer the C++ approach of using constructors and destructors to automatically acquire resources (like locks and files) by declaring variables within some block scope, and release them once the scope is left.
1 comments

Javascript with and python with are completely separate things.

Javascript with comes from Pascal with (which was perhaps copied from somewhere else) and is used to modify variable scope.

    with (my.long.variable.reference) {
        a = 1;
        b = 2;
    }
is equivalent to:

    my.long.variable.reference.a = 1;
    my.long.variable.reference.b = 2;

or at least, it might be ... due to Javascript's dynamic and typeless nature you might not know for sure what will happen until runtime. Which is one reason it's now deprecated and not allowed in strict mode. In pascal, variables have a type, records have fields, and these are known at compile time so that's not an issue.

https://wiki.freepascal.org/With

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

I knew about the Pascal "with", but I didn't know JavaScript had the same construct.

That kind of "with" is a lot less intuitive to me.

I was responding with Python's "with" because it sounded like they were talking about programming languages in general, but now I can see they were obviously talking about JavaScript's "with" given this context.