“胖箭"什么时候出现(=>) 绑定到“this";实例 [英] When does the "fat arrow" (=>) bind to "this" instance

查看:26
本文介绍了“胖箭"什么时候出现(=>) 绑定到“this";实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

粗箭头可以在不同的设置中使用,但不知何故不能总是绑定到我想要的实例.

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

推荐答案

胖箭头绑定3次

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

1.声明方法时

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

1. When declaring a method

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

class A
    somemethod: (paramlist) =>

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

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

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

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()

这是对应的Javascript

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.

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

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

那么对应的Javascript会是这样的

Then the corresponding Javascript will look like this

var foo,
  _this = this;

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

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

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

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

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.

这篇关于“胖箭"什么时候出现(=>) 绑定到“this";实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆