Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - 为什么任何JavaScript代码都想“削减绑定”???(Why does any JavaScript code want to “cut the binding”?)

The reason of using a

(使用一个的原因)

(0, foo.fn)();

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

(是削减绑定this将不再绑定到foo而是绑定到全局对象。)

But what is the reason why any JavaScript code (or Google's JS code) would want to cut the binding?

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

(and is it an anti-pattern or not?)

((是否是反模式?))

  ask by nopole translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(此类代码通常由编译器(如Babel)生成,以将现代JavaScript(使用该规范的最新功能)转换为得到更广泛支持的JavaScript版本。)

Here is an example where this transpilation pattern occurs:

(这是发生这种转嫁方式的一个例子:)

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

(假设在转译之前我们有以下原始代码:)

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

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

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

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

But here we would execute myfunc with mymodule as this value, which is not happening in the original code.

(但是这里我们将使用mymodule作为this值执行myfunc ,这在原始代码中不会发生。)

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参考-如何不寻常的,甚至没用,以至于使用thismyfunc可能是(因为在原始版本中也将是undefined )。)

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.

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

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

(这就是使用逗号运算符消除该差异的原因:)

(0, mymodule.myfunc)();

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.

(当然,在您自己编写的代码中,您永远不会有这种模式的好用例,因为您一开始就不会在myfunc中使用this 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...