Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've looked up some JSSS code examples, and it seems like it's pretty much the only type of code where the "with" keyword makes sense:

  <style type="text/javascript">
  tags.H1.color = "red";
  tags.p.fontSize = "20pt";

  with (tags.H3) {
    color = "green";
  }
  with (tags.H2) {
    color = "red";
    fontSize = "16pt";
    marginTop = "4cm";
  }
  </style>


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.


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.


It was also a rarely-used classic way to deal with variable references that changed in a loop:

  var values = [];
  for (var i = 0; i < 3; i++) {
    values.push(function() { console.log(i); });
  }
  for (var j = 0; j < 3; j++) {
    values[j]();
  }
This would log 3, 3 times. The usual fix (before the variety of modern ways) was to use an IIFE in the first loop:

  for (var i = 0; i < 3; i++) {
    (function(i) {
      values.push(function() { console.log(i); });
    })(i);
  }
Alternatively, this works:

  for (var i = 0; i < 3; i++) {
    with ({i: i}) {
      values.push(function() { console.log(i); });
    }
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: