10

胖箭头可以在不同的设置中使用,但它并不总是绑定到我想要的实例。

4

1 回答 1

14

胖箭绑定了3次

  1. 声明方法时
  2. 在方法中声明函数时
  3. 在全局上下文中声明函数时

1.声明方法时

当 Coffeescript 编译器在类声明中遇到以下语法模式时

class A
    somemethod: (paramlist) =>

这将在类 A 的构造函数中产生以下代码

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

那就是该实例的定义是用函数的绑定版本覆盖初始分配

2.在方法中声明函数时

当你在方法中定义一个带有粗箭头的函数时,Coffeescript 编译器会自动创建一个闭包,并将外部方法的this隐藏到变量 _this中。内部函数中对@的任何引用都将 在生成的 javascript 代码中使用变量_this

somemethod: ->
   => @someCall()

这是相应的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();
    };
};

没有粗箭头的函数定义不会为您创建该闭包。

3. 在全局上下文中声明函数时

如果您像这样定义一个自由浮动函数(意思是类中的方法而不是另一个函数/方法中的方法)

foo = => @bar

那么对应的Javascript会是这个样子

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.

于 2012-11-01T19:33:26.597 回答