coffeescript icon indicating copy to clipboard operation
coffeescript copied to clipboard

Bug: Wrong `this` in bound methods of nested classes

Open gsamokovarov opened this issue 5 years ago • 1 comments

While upgrading an application to CS2 we ran into the following issue in an obscure usage of nested classes.

Screenshot 2019-07-18 at 16 33 10

As you can see, the nested bound method thought its this is the parent class. This seems to happen on a "parse" level, because it's replaced in the code. This lead to tricky to catch bug on our side.

gsamokovarov avatar Jul 18 '19 13:07 gsamokovarov

I've been looking into this and while I don't have a solution, I believe I have a work-around which may or may not be useful to you. If you assign the bound method to a var, the generated method references the inner class name instead of the outer one.

class Outer
  class Inner
    bound: bound = =>
      @name

Compiles to

var Outer;

Outer = (function() {
  var Inner;

  class Outer {};

  Inner = (function() {
    var bound;

    class Inner {};

    Inner.prototype.bound = bound = () => {
      return Inner.name;
    };

    return Inner;

  }).call(this);

  return Outer;

}).call(this);

I hope someone finds this useful.

rdeforest avatar Dec 08 '19 05:12 rdeforest