问题 jQuery源代码中的returnTrue和returnFalse函数


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

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

在jQuery中经常调用它们。是否有理由不简单地用布尔值替换函数调用 true 要么 false


8148
2018-02-07 07:32


起源

除了以下答案之外,单个定义可能还有性能原因而不是全部匿名函数。 - Jim Deville


答案:


它像这样使用:

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 , isPropagationStoppedisImmediatePropagationStopped 在DOM事件级别3 sepc中定义。

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


4
2018-02-07 07:44



那么为什么不使用变化 isImmediatePropagationStopped 而是一个实例属性?所以我们可以像使用它一样 if (event.isImmediatePropagationStopped) 代替 if (event.isImmediatePropagationStopped())? - rexcfnghk
它也是W3C规范的一部分(不知道为什么你删除了评论): w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/... - Jim Deville
因为api是由w3c定义的: w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/... - Rain Diao
@JimDeville我想添加更多细节。但不能编辑它,超过五分钟过去。 - Rain Diao
接受w3c参考 - rexcfnghk


如果对象属性,函数参数等需要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;
},

特别是因为他们 被经常打电话


11
2018-02-07 07:40



你能解释一下为什么不能简单地使用 someProperty: true? - rexcfnghk
true 与返回true的函数不同。如果某些属性或参数需要函数,则无法用文字替换它 true。 - Salman A