in PHP we have the neat use
keyword for allowing the usage of 'external' variables when using closures, like the following:
$tax = 10;
$totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use'
return ($price * $quantity) * ($tax + 1.0);
};
If we omit the use ($tax)
part, it will throw an error, which I like a lot.
Similarly in C++ 11, we do the same, specifying the external variables, called capture list, with brackets:
float tax = 10;
auto totalPrice = [tax](int quantity, float price){ //mandatory []
return (price*quantity) * (tax + 1.0);
};
As in php, it will throw an error if the capture list is omitted.
In Javascript, we don't have an equivalent to this use
keyword (or c++ []), we just do:
var tax = 10;
var totalPrice = function (quantity, price){ //no need for 'use' or similar
return (price * quantity) * (tax + 1.0); //tax is usable here :(
};
I don't like much that freedom, I strongly prefer to specify the variables that will be accessible by the closure function or get an error otherwise, for reasons outside the scope of this question.
So, I was wondering, is there a special keyword or operator for this in ES6, or in any language that transpiles to javascript? (CoffeeScript, TypeScript, etc) If so, in which language and what's the syntax?
Ideally I'd like to detect in transpilation time (or before), when a variable hasn't been explicitly 'authorized' to be used in a closure, pretty much like PHP/C++.
Thanks in advance
PS: Please don't ask me why I want this in js-like language, that debate is another topic.
EDIT: A linter that performs this check would also help