gpt4 book ai didi

javascript - 在 JavaScript 中链接 'bind' 和 'call'?

转载 作者:数据小太阳 更新时间:2023-10-29 05:29:29 26 4
gpt4 key购买 nike

当我阅读这篇文章时 answer , 找到 var g = f.call.bind(f);。乍一看我无法理解这一点。

那么它有没有一些直接的含义,有一些合适的使用场景呢?

进一步,当您在链接中使用 call(or apply)bind 或两者时,会发生什么?有什么法律吗?

最佳答案

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

我假设您熟悉 .call().bind() 函数方法?嗯,它将 f.call 方法绑定(bind)到函数 f

请注意 f.call 只是 Function.prototype.call,我们将它作为 f 上的属性访问并不重要> 因为我们不在这里调用它。

So does it has some direct meaning?

当我们查看等效的 ES6 时,它可能会变得更加明显:

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

好吧,现在您知道它的作用了,是的。它可以采用原型(prototype)方法并将其转换为将实例作为第一个参数的静态函数。一个例子:

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

Are there any laws for further chaining call/apply/bind?

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

但是,通过将它们作为参数传递给彼此,您可以做到 some crazy things这些或多或少有用。

关于javascript - 在 JavaScript 中链接 'bind' 和 'call'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31198503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com