为什么任何JavaScript代码都想“剪切绑定"? [英] Why does any JavaScript code want to "cut the binding"?

查看:49
本文介绍了为什么任何JavaScript代码都想“剪切绑定"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用a的原因

(0, foo.fn)();

剪切绑定:this将不再绑定到foo,但将绑定到全局对象.

is to cut the binding: the this will not longer be bound to foo but will be bound to the global object.

但是,为什么任何JavaScript代码(或Google的JS代码)想要削减绑定的原因是什么? (是否是反模式?)

But what is the reason why any JavaScript code (or Google's JS code) would want to cut the binding? (and is it an anti-pattern or not?)

推荐答案

此类代码通常由编译器(如Babel)生成,以便转换现代JavaScript(使用规范的最新添加内容)-到更广泛支持的JavaScript版本.

This kind of code is typically generated by transpilers (like Babel), in order to convert modern JavaScript -- that uses the most recent additions to the specification -- to a JavaScript version that is more widely supported.

以下是发生这种移栽模式的示例:

Here is an example where this transpilation pattern occurs:

比方说,在移植之前,我们有以下原始代码:

Let's say we have this original code before transpilation:

import {myfunc} from "mymodule";
myfunc();

要制作与ES5兼容的代码,您可以执行以下操作:

To make this ES5-compatible code, you could do this:

"use strict";    
var mymodule = require("mymodule");    
mymodule.myfunc();

但是在这里,我们将以mymodule作为this值执行myfunc,这在原始代码中不会发生.尽管这并不总是一个问题,但最好还是确保该函数的行为与原始版本相同,即使该函数使用的是this引用-多么不寻常甚至可能对在myfunc中使用this毫无用处(因为在原始版本中也将是undefined).

But here we would execute myfunc with mymodule as this value, which is not happening in the original code. And although that might not always be an issue, it is better to make sure the function behaves just like it would in the original version, even if that function would use a this reference -- how unusual or even useless that use of this in myfunc might be (because also in the original version it would be undefined).

因此,例如,如果原始代码由于函数中的this.memberFun()引用而引发错误,那么它也将引发已编译的版本.

So for instance, if the original code would throw an error because of a this.memberFun() reference in the function, it will also throw in the transpiled version.

这就是使用逗号运算符来消除这种差异的原因:

So that is were the comma operator is used to get rid of that difference:

(0, mymodule.myfunc)();

在您自己编写的代码中,准予使用该模式,因此永远不会有一个很好的用例,因为您一开始就不会在myfunc中使用this.

Granted, in code that you write yourself, you would never have a good use case for this pattern, as you would not use this in myfunc in the first place.

这篇关于为什么任何JavaScript代码都想“剪切绑定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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