coffeescript
coffeescript copied to clipboard
Bug: Wrong `this` in bound methods of nested classes
While upgrading an application to CS2 we ran into the following issue in an obscure usage of nested classes.
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.
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.