CoffeeScript 1.9.0 changes to variable names

2019-07-21 04:08发布

问题:

In the CoffeeScript 1.9.0 ChangeLog, I read:

Changed strategy for the generation of internal compiler variable names. Note that this means that @example function parameters are no longer available as naked example variables within the function body.

I don't quite understand what this means for me as a user. Is this somehow an incompatible change? Can I safely upgrade to version 1.9.0?

回答1:

It depends. Yes, this change is incompatible. If you had written tests, you could check if it affects you. Take this little piece of code:

example = "new"
obj = method: (@example) -> console.log(example)
obj.method "old"

In 1.8 this would print old. In the new version, this prints new.

In the older version, @example would be translated to example in the method parameters. So you're accessing obj.method's function parameter in the old version.
In the new version you're accessing the example variable of the outer scope. a.example still gets set to "old" in both cases.

Here you can see the difference in the generated JS code:

-// Generated by CoffeeScript 1.7.1
+// Generated by CoffeeScript 1.9.0
 (function() {
   var example, obj;

   example = "new";

   obj = {
-    method: function(example) {
-      this.example = example;
+    method: function(_at_example) {
+      this.example = _at_example;
       return console.log(example);
     }
   };

   obj.method("old");

 }).call(this);


回答2:

See Patrick J. S.’ answer for what the change means.

See How do I find cases of CoffeeScript 1.9.0 breaking change in my code? for how to know if you can upgrade safely, and what you need to do if not.