什么时候"胖箭头"(=>)绑定到"this"实例

rob*_*kuz 10 this coffeescript arrow-functions

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

rob*_*kuz 14

胖箭有3次结合

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

1.声明方法时

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

class A
    somemethod: (paramlist) =>
Run Code Online (Sandbox Code Playgroud)

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

this.somemethod = __bind(this.somemethod, this);
Run Code Online (Sandbox Code Playgroud)

也就是说,该实例的定义是使用函数的绑定版本覆盖初始赋值

2.在方法中声明函数时

当你的方法中定义与脂肪箭头的函数的CoffeeScript编译器自动创建一个封闭和和阴影外方法的入变量 _this.内部函数中对@的任何引用都将 在生成的javascript代码中使用变量_this

somemethod: ->
   => @someCall()
Run Code Online (Sandbox Code Playgroud)

这是相应的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();
    };
};
Run Code Online (Sandbox Code Playgroud)

没有胖箭头的函数定义不会为您创建闭包.

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

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

foo = => @bar
Run Code Online (Sandbox Code Playgroud)

然后相应的Javascript将如下所示

var foo,
  _this = this;

foo = function() {
    return _this.bar;
};
Run Code Online (Sandbox Code Playgroud)

这里有趣的是,被分配给_ this,这使得foo的定义能够关闭_ this.

但重要的是,始终是执行环境的全局上下文.如果您在浏览器中它将是窗口对象.如果您正在运行node.js,它将是您刚刚运行的模块.

警告:您不应该定义任何访问全局上下文的函数.这需要麻烦.