12

我不禁注意到jQuery的源代码中有两个看似无用的函数(对于v1.9.1,它是第2702行和第2706行):

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

这两者在 jQuery 中经常被调用。他们为什么不简单地将函数调用替换为布尔值true或是否有原因false

4

2 回答 2

12

如果对象属性、函数参数等需要 afunction你应该提供 afunction而不是 a boolean

例如在原生 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;
},

特别是因为它们经常被调用

于 2013-02-07T07:40:08.477 回答
4

它是这样使用的:

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来存储状态。

通过这个技巧,您可以在此处切断一堆用于保持真/假状态的实例属性,例如_isImmediatePropagationStopped_isDefaultPrevented

因此,在我看来,这只是代码风格的问题,没有对错之分。

PS:事件的查询方法,如isDefaultPrevented,,在DOM事件级别3 sepc中定义isPropagationStoppedisImmediatePropagationStopped

规格:http ://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-Event-isImmediatePropagationStopped

于 2013-02-07T07:44:01.050 回答