12

jQuery のソース コードには、一見役に立たない関数が 2 つあります (v1.9.1 の場合、2702 行目と 2706 行目です)。

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

どちらも jQuery 内で頻繁に呼び出されます。true関数呼び出しを単純にブール値またはで置き換えない理由はありfalseますか?

4

2 に答える 2

12

オブジェクトのプロパティ、関数の引数などでfunctionが必要な場合は、functionではなくを指定する必要があります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このトリックを使用すると、ここで true/false ステータスを保持するために、_isDefaultPreventedなどのインスタンス プロパティの束を切り取ることができます。

私の意見では、これは単なるコード スタイルの問題であり、正しいか間違っているかではありません。

PS: 、 などのイベントのクエリ メソッドは、isDefaultPreventedDOMイベント レベル 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 に答える