Why doesn't the fat arrow bind to this when I

2019-03-03 19:56发布

问题:

I have the following code that declares a method which is advised by an intermediary function before the function result is assigned to a prototype slot.

class A
    somemethod: advise => @dosomething()

Why does the fat arrow does not bind to the instance in this case?

回答1:

Simple answer

When an intermediary is put between the prototype slot name and function definition you break the syntactic pattern that makes the CS emit the binding code in the constructor

class A
    foo: (paramlist) =>
    bar: ()=>
    baz: =>

all these method definitions emit this code in the generated Javascript constructor

function A() {
    this.foo = __bind(this.foo, this);
    this.bar = __bind(this.bar, this);
    this.baz = __bind(this.baz, this);
}

If you put something in between you break that syntactic pattern by which the Coffeescript compiler can recognize that pattern and generated the necessary code.

class A
    helpWhereIsMyMethod: processTheFollowing => @doSomething()

In this case no bind calls in the constructor are generated

More complex Answer

When you define a prototype slot (name) and immediately assign a (anonymous) function to it you have effectively created a handle by which you can later access that function and "process" it or call it (most of the cases).

If you pipe your function into another function (the intermediary) before binding the result to a prototype slot you create effectively an anonymous function that you can't access later.

So the Coffeescript compiler doesn't know how to emit the bind code in the constructor because during object creation time the access to the anonymous function is not given anymore.

Also the intermediary function could generate code of its own and emit this new code to be bound to the prototype slot.