我不禁注意到jQuery源代码中有两个看似无用的函数(对于v1.9.1,是第2702行和第2706行):
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
这两者在 jQuery 中经常被调用。为什么他们不简单地将函数调用替换为 bool 值 true
或 false
?
最佳答案
如果对象属性、函数参数等需要一个函数
,您应该提供一个函数
,而不是一个 bool 值
。
例如在原生 JavaScript 中:
var a = document.createElement("a");
a.href = "http://www.google.com/";
/*
* see https://developer.mozilla.org/en-US/docs/DOM/element.onclick
* element.onclick = functionRef;
* where functionRef is a function - often a name of a function declared
* elsewhere or a function expression.
*/
a.onclick = true; // wrong
a.onclick = returnTrue; // correct
a.onclick = function() { return true; }; // correct
另外,写作:
someProperty: returnTrue,
比写更方便:
someProperty: function(){
return true;
},
特别是因为它们经常被调用。
关于javascript - jQuery 源代码中的 returnTrue 和 returnFalse 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14745912/