简体   繁体   English

为什么对同一函数的两个绑定返回不同的值

[英]Why two bindings to the same function return different values

When binding a function to the same context, the resulting reference is different every time. 将函数绑定到同一上下文时,结果引用每次都不同。

 function foobar() { return 1; } var foo = foobar.bind(this); var bar = foobar.bind(this); console.log(foo === bar); // Nope 

  1. Does that code copy the function every time? 该代码是否每次都复制该功能?
  2. Wouldn't there be any benefit in caching that behavior? 缓存这种行为不会有任何好处吗?
  3. Is it implementation specific? 具体是实施吗?
  4. Or is it specified somewhere in ecmascript specification? 或者它是在ecmascript规范中指定的?

是的, Function.prototype.bind()每次都会创建一个新函数。

Does that code copy the function every time? 该代码是否每次都复制该功能?

Whether or not it copies the original function is an implementation detail of the underlying JS engine. 它是否复制原始函数是底层JS引擎的实现细节。

The return value of bind is a new function, and you'll get a new one each time you call bind . bind的返回值是一个新函数,每次调用bind时都会得到一个新函数。

Wouldn't there be any benefit in caching that behavior? 缓存这种行为不会有任何好处吗?

There might be a mild performance gain to be had in caching the resulting function, but probably not enough to worry about unless you are generating hundreds of bound copies of the same function. 在缓存生成的函数时可能会有轻微的性能提升,但可能不足以担心,除非您生成数百个相同函数的绑定副本。 Beware of premature optimization . 注意过早优化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM