我不禁注意到jQuery的源代码中有两个看似无用的函数(对于v1.9.1,它的第2702行和第2706行):
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
在jQuery中经常调用它们。是否有理由不简单地用布尔值替换函数调用 true
要么 false
?
我不禁注意到jQuery的源代码中有两个看似无用的函数(对于v1.9.1,它的第2702行和第2706行):
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
在jQuery中经常调用它们。是否有理由不简单地用布尔值替换函数调用 true
要么 false
?
它像这样使用:
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
这里 isImmediatePropagationStopped
是一个查询 方法。像这样使用 event.isImmediatePropagationStopped()
当然,您可以定义一个实例方法,如:
event.prototyoe.isImmediatePropagationStopped = function() { return this._isImmediatePropagationStopped };
stopImmediatePropagation: function() {
this._isImmediatePropagationStopped = true; //or false at other place.
this.stopPropagation();
}
但是你必须引入一个新的实例属性 _isImmediatePropagationStopped
存储状态。
有了这个技巧,你可以在这里切断一堆实例属性for hold true / false status,比如 _isImmediatePropagationStopped
, _isDefaultPrevented
等等
所以,在我看来,这只是代码风格的问题,而不是对错。
PS:关于事件的查询方法,比如 isDefaultPrevented
, isPropagationStopped
, isImmediatePropagationStopped
在DOM事件级别3 sepc中定义。
如果对象属性,函数参数等需要a function
你应该提供一个 function
不是 boolean
。
例如在vanilla 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;
},
特别是因为他们 被经常打电话。