Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

coffeescript - When does the "fat arrow" (=>) bind to "this" instance

The fat arrow can be used in different settings but it somehow doesn't always bind to the instance I want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The fat arrow binds at 3 occasions

  1. when declaring a method
  2. when declaring a function within a method
  3. when declaring a function in global context

1. When declaring a method

When the Coffeescript compiler encouters the following syntactical pattern within a class declaration

class A
    somemethod: (paramlist) =>

This will yield the following code within the constructor of class A

this.somemethod = __bind(this.somemethod, this);

That is the definition for that instance is overwriting the initial assignment with a bound version of the function

2. When declaring a function within a method

When you define a function with a fat arrow within a method the Coffeescript compiler automatically creates a closure and and shadows this of the outer method into the variable _this. Any reference to @ within the inner function will use the variable _this in the generated javascript code

somemethod: ->
   => @someCall()

And this is the corresponding Javascript

A.prototype.somemethod = function() {
    //_this references this
    var _this = this;
    return function() {
        //and _this is now used within the inner function
        return _this.someCall();
    };
};

A definition of a function without the fat arrow doesn't create that closure for you.

3. When declaring a function in global context

If you define a free floating function (meaning as a method in a class and not within another function/method) just like this

foo = => @bar

Then the corresponding Javascript will look like this

var foo,
  _this = this;

foo = function() {
    return _this.bar;
};

The interesting thing here again is that this is being assigned to _this which enables the definition of foo to close over _this.

The important part however is that this is always the global context of your execution environment. If you are in the browser it will be the window object. If you are running node.js it will be the module you are just running.

Warning: You shouldn't define any function accessing your global context anyway. This calls for trouble.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...