在JavaScript中链接'绑定'和'调用'?

问题描述:

当我阅读答案时,找到 var g = f.call.bind(f ); 。我第一次看不到这一点。

When I reading this answer, find var g = f.call.bind(f);. I can't understand this with my first sight.

那么它有一些直接含义,并且有一些适当的使用场景吗?

So does it has some direct meaning, and has some appropriate usage scenarios?

当你在链接中使用调用(或应用) bind 或两者时,会发生什么?是否有一些法律?

And further when you using call(or apply) or bind or both in chaining, what will happen? Is there some laws?


var g = f.call。绑定(F); 。我第一次看不到这一点。

var g = f.call.bind(f);. I can't understand this with my first sight.

我假设你熟悉 .call() .bind() 功能方法?好吧,它将 f.call 方法绑定到函数 f

I assume you're familar with both the .call() and .bind() Function methods? Well, it binds the f.call method to the function f.

请注意 f.call 只是 Function.prototype.call ,这没关系我们在 f 上将其作为属性访问,因为我们不在此处调用它。

Notice that f.call is just Function.prototype.call, it doesn't matter that we access it as a property on f because we don't call it here.


So does it has some direct meaning?

当我们看看ES6等价物时,它可能会变得更加明显:

It might become more obvious when we look at the ES6 equivalent:

(Function.prototype.call).bind(f) // or
(f.call).bind(f) // is basically
(...args) => f.call(...args) // or more clear
(ctx, ...args) => f.call(ctx, ...args)




是否有一些适当的使用场景?

Does it have some appropriate usage scenarios?

好吧,既然你知道它做了什么,是的。它可以采用原型方法并将其转换为静态函数,该函数将实例作为第一个参数。例如:

Well, now that you know what it does, yes. It can take a prototype method and transforms it to a static function that takes the instance as the first argument. An example:

function Example(n) { this.name = n; }
Example.prototype.display = function() { console.log(this.name); }

Example.display = Function.call.bind(Example.prototype.display);

var e = new Example;
e.display(); // is the same as
Example.display(e);




是否有进一步链接的法律致电 / apply / bind

是:一如既往,只有链中的最后一个属性实际上被称为方法。在上面的例子中, f.call.bind(...) Function.prototype.call.bind(...)$之间没有区别c $ c>或 Function.call.apply.bind.call.bind(...) - 它总是调用 bind 调用

Yes: as always, only the last property in the chain is actually called as a method. In the above example, theres no difference between f.call.bind(…), Function.prototype.call.bind(…) or Function.call.apply.bind.call.bind(…) - it always calls bind on call.

然而,通过将它们作为参数传递给彼此,你可以做一些 疯狂 小吃或多或少有用。

However, by passing them as arguments to each other, you can do some crazy things which are more or less useful.