当我通过中间函数管道我的方法定义时,为什么胖箭头不绑定到这个? [英] Why doesn't the fat arrow bind to this when I pipe my method definition thru an intermediary function?

查看:9
本文介绍了当我通过中间函数管道我的方法定义时,为什么胖箭头不绑定到这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码声明了一个中间人建议的方法函数结果分配给原型槽之前的函数.

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?

推荐答案

简单回答

当在原型槽名称和函数之间放置一个中介时定义你打破了使 CS 发出的句法模式构造函数中的绑定代码

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: =>

所有这些方法定义在生成的 Javascript 构造函数中发出此代码

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);
}

如果你在两者之间加入一些东西,你就会打破那个句法模式,Coffeescript 编译器可以识别该模式并生成必要的代码.

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

当你定义一个原型槽(名称)并立即分配一个(匿名)函数时对它,您已经有效地创建了一个句柄,您以后可以通过该句柄访问该函数并处理"它或调用它(大多数情况下).

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.

所以 Coffeescript 编译器不知道如何在构造函数中发出绑定代码因为在对象创建期间,不再提供对匿名函数的访问.

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.

这篇关于当我通过中间函数管道我的方法定义时,为什么胖箭头不绑定到这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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