网卡绑定功能
We oftentimes assume that "native" APIs within the browser are fast -- at least faster than shims we create or have been using. I was surprised to recently read this StackOverflow thread which asserts that Function.prototype.bind
is much slower than what you can shim. The thread cites JS Perf links (which unfortunately don't work at the moment) but assuming the statements about speed are correct, let's check out how we can create our own bind
function.
我们通常会假设浏览器中的“本机” API速度很快-至少比我们创建或一直使用的垫片更快。 我最近读了这个StackOverflow线程感到惊讶, 该线程断言Function.prototype.bind
比您可以填充的要慢得多。 该线程引用了JS Perf链接(不幸的是,目前暂时不起作用),但是假设有关速度的语句是正确的,让我们检查一下如何创建自己的bind
函数。
JavaScript绑定功能 (JavaScript bind Function)
Creating a basic bind
function is incredibly easy, as the aforementioned provided:
如前所述,创建基本bind
函数非常简单:
function bind (fn, ctx) {
return function bound () {
return fn.apply(ctx, arguments);
};
}
// Usage:
bind(this.someFunction, this);
This is the simplest possible bind
function but it doesn't accommodate for additional arguments you can provide to bind
, which is why a more complete function is more complicated:
这是可能的最简单的bind
函数,但不能容纳您可以提供给bind
其他参数,这就是为什么更完整的函数更复杂的原因:
function bind (fn, ctx/* , arg1, arg2 */) {
return (function (prependedArgs) {
return function bound () {
// Concat the bound function arguments with those passed to original bind
var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
return fn.apply(ctx, args);
};
})(Array.prototype.slice.call(arguments, 2));
// Usage
// anotherArg is first arg to onClick, then the event
bind(this.onClick, this, anotherArg);
This more complete method merges the passed-in arguments with the arguments provided to the individual function call (an Event
, for example, if bind
was used on an click
event).
这更完整的方法合并传入的与提供给各个功能调用的参数(参数的Event
,例如,如果bind
了上使用click
事件)。
I cannot tell you with any certainty that Function.prototype.bind
is in fact super slow, and if so, it's across every browser. It is interesting, however, to explore these native API speeds in an effort to make our apps as fast as possible.
我无法肯定地告诉您Function.prototype.bind
实际上超级慢,如果是这样,它将遍历所有浏览器。 但是,探索这些本机API的速度以使我们的应用程序尽可能快地运行很有趣。
Know more about bind speed? Please share!
进一步了解绑定速度? 请分享!
网卡绑定功能