代码之家  ›  专栏  ›  技术社区  ›  Konrad

从通常返回引用的javascript函数中提前返回的最佳方法

  •  0
  • Konrad  · 技术社区  · 16 年前

    假设我们有一个函数的形式:

    function getReferenceToFoo( idName )
    {
        if( ! document.getElementById( idName ) )
        {
            return;
        }
        ... 
        // else return reference to element normally
    }
    

    按返回类型指示故障的最佳方式是什么?根据我的想法,我可以做以下一项:

    1. 返回“null”

    哪一个是最佳实践?为什么?

    3 回复  |  直到 16 年前
        1
  •  4
  •   anddoutoi    13 年前

    在JavaScript中,所有函数都返回,即使您没有显式地让它们返回。如果没有return语句,函数将返回 undefined new 语句,函数将返回 this .

    function doFoo()
    {
        // do nothing
    }
    

    ,

    function doFoo()
    {
        return;
    }
    

    和

    function doFoo()
    {
        return undefined;
    }
    

    对JavaScript引擎来说都是一样的。

    null 作为JavaScript中的返回值。 是一个对象,执行类型检查可能会导致奇怪的逻辑。如果你使用 作为返回,您最好更改 if() 更明确地说。

    我建议你只回来 无效的 失效值 来自期望返回值是某种对象的函数。如果期望返回值是某种原始的,我会考虑。

    foo = getReferenceToFoo('myID');
    // foo might be a reference or null
    if (null !== foo) {
        // do things
    }
    

    document.getElementById 返回 无效的 如果它找不到任何东西。

    我知道这是一个反模式,但我确实使用:

    var myElmnt;
    if ((myElmnt = document.getElementById('myId')))
    {
        // do stuff with myElmnt
    }
    

    是的,我知道,我会在地狱里燃烧。

        2
  •  1
  •   instanceof me    16 年前

    归还某物 ,我将返回null,因为null的目的就是表示null内容。

    Wikipedia for Null :

    Null是一个特殊的指针值(或其他类型的对象引用),用于表示指针有意不指向(或引用)对象。

        3
  •  -2
  •   Oli    16 年前

    返回false或nothing。只是 return 如果您执行以下操作,则将作为null:

    foo = getReferenceToFoo('myID');
    if (foo) {
        // do things
    }