我刚刚通读了this article关于命名函数表达式及其与 IE <= 8 的不兼容性。
我特别对一个声明感到好奇:
A common pattern in web development is to “fork” function definitions based on some kind of a feature test, allowing for the best performance.
取自他页面的例子:
var contains = (function() {
var docEl = document.documentElement;
if (typeof docEl.compareDocumentPosition != 'undefined') {
return function(el, b) {
return (el.compareDocumentPosition(b) & 16) !== 0;
};
}
else if (typeof docEl.contains != 'undefined') {
return function(el, b) {
return el !== b && el.contains(b);
};
}
return function(el, b) {
if (el === b) return false;
while (el != b && (b = b.parentNode) != null);
return el === b;
};
})();
当我看到这个时,我的第一 react 是这很难维护。以这种方式编写的代码本身并不易于理解。
在这种情况下,我们可以编写一个嵌套的 if
函数,而不是在另一个函数中有条件地定义一个函数,然后在声明外部函数后立即调用该函数。它会更长,但在我看来更容易理解(尽管我来自 C/C++/Java)。
我更喜欢包含一些测试编号或解释这些函数在运行时有何不同的答案。
最佳答案
效率很高。注意最后的 ();
。这将立即执行并将外部函数的结果分配给 contains
。这比每次使用函数contains
时都执行底层逻辑要高效得多。
不是每次调用 contains()
时都检查 compareDocumentPosition
是否存在,而是在代码首次执行时检查一次。 compareDocumentPosition
存在或不存在的事实不会改变,因此只检查一次是理想的。
关于Javascript: fork 函数声明的效率有多高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5506877/