jQuery源代码中的returnTrue和returnFalse函数

rex*_*ghk 11 javascript jquery

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

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

在jQuery中经常调用它们.是否有一个原因,他们不会简单地替代函数调用用布尔truefalse

Sal*_*n A 11

如果对象属性,函数参数等期望function你应该提供一个function不是a 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
Run Code Online (Sandbox Code Playgroud)

另外,写作:

someProperty: returnTrue,
Run Code Online (Sandbox Code Playgroud)

比写作更方便:

someProperty: function(){
    return true;
},
Run Code Online (Sandbox Code Playgroud)

特别是因为他们经常被召唤.

  • `true`与返回true的函数不同.如果某些属性或参数需要函数,则不能用文字"true"替换它. (4认同)

Rai*_*iao 4

它是这样使用的:

stopImmediatePropagation: function() {
    this.isImmediatePropagationStopped = returnTrue;
    this.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)

这里isImmediatePropagationStopped有一个查询方法。像这样使用event.isImmediatePropagationStopped()

当然,你可以定义一个实例方法,例如:

event.prototyoe.isImmediatePropagationStopped = function() { return this._isImmediatePropagationStopped };

stopImmediatePropagation: function() {
    this._isImmediatePropagationStopped = true; //or false at other place.
    this.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)

但您必须引入一个新的实例属性_isImmediatePropagationStopped来存储状态。

通过这个技巧,您可以切断一堆实例属性以在此处保持 true/false 状态,例如等_isImmediatePropagationStopped_isDefaultPrevented

因此,在我看来,这只是代码风格的问题,无关对错。

PS:事件的查询方法,如isDefaultPreventedisPropagationStoppedisImmediatePropagationStopped等在 DOM event level 3 sepc 中定义。

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