为什么jquery有一个函数“returnTrue()”和“returnFalse()”只返回true和false?

时间:2014-03-10 15:08:17

标签: javascript jquery

根据https://github.com/jquery/jquery/blob/9434e03193c45d51bbd063a0edd1a07a6178d33f/src/event.js#L21-L27 在jquery中的event.js中有两个函数返回true和false: 来自events.js

function returnTrue() {
  return true;
}

function returnFalse() {
  return false;
}

我知道他们很好。但我不明白这个的原因。

2 个答案:

答案 0 :(得分:5)

您是否看过并看到它们的使用位置?

它们用作需要返回布尔函数的赋值的存根。

例如,在同一文件的第670行:

    this.isDefaultPrevented = returnTrue;

isDefaultPrevented是一个函数。因此,它需要一个返回true的函数作为默认功能。

答案 1 :(得分:0)

考虑一下他们的用法:

// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
        // Support: Android < 4.0
        src.defaultPrevented === undefined &&
        src.getPreventDefault && src.getPreventDefault() ?
    returnTrue :
    returnFalse;

在多个功能中执行此类或类似操作。键入returnTrue更容易,而不是每次都要拼出function() { return true; },不是吗?代码重用和可读性。