【问题标题】:Overloading Functions in JavaScriptJavaScript 中的函数重载
【发布时间】:2012-08-25 09:55:30
【问题描述】:

我已经使用 jQuery 一年了,但我仍然不明白这段代码是如何工作的:

alert($('#elementID').val()); // It gets the value of element

$('#elementID').val('setting Value'); // the same function is setting value

jquery 的一些其他功能也可以像.html() 一样做同样的事情

我想知道这个东西是怎么实现的?他们如何重载 javascript 函数?

【问题讨论】:

  • 它只是检查函数中是否给出了一个值,如果没有,它检索当前值?
  • @adeneo 是的,确实如此,但事情是如何发生的,我不知道任何技术可以使用相同的功能来做到这一点
  • 嗯,在 C++ 中,我们可以使用默认参数来模拟重载,这里是 javascript 的可选参数。

标签: javascript jquery overloading


【解决方案1】:

javascript 中没有重载,所以像这样的壮举是使用可选参数来执行的。 JavaScript 允许您在不指定参数的情况下调用函数。例如:

function val(text)
{
  if (arguments != null && arguments.length > 0) {
    alert("i'm setting value here to " + text);
  } else {
    alert("i'm getting value here");
  }
}

val(); // alerts value getter
val('hi!'); // alerts value setter and the message

这个例子是为了指出arguments collection which you get in every function。每个函数都可以将它的参数作为一个集合来获取,并可以相应地执行它的逻辑。但是,显示的示例在现实世界中的写法会有所不同:

function val(text)
{
  if (typeof text === "string") {
    alert("i'm setting value here to " + text);
  } else {
    alert("i'm getting value here");
  }
}

您没有传递给函数的每个参数都会获得undefined(不是null)的“值”。这使您可以使用最短的逻辑表达式。您可以在if 语句中使用任何值。 nullundefined 的变量将被简单地评估为 false

正如下面的评论指出,如果text 参数为空字符串if (text) 将返回false。因此,对于文本参数,请按类型检查参数。

您也可以read about null and undefined differences

【讨论】:

  • 在您的第一个代码中 sn-p var "arguments" 是默认关键字吗?或者你在哪里定义的?
  • 参数是默认关键字。我还提供了 Mozilla 开发者网络的链接,您可以在其中阅读。
  • @Rupesh:他们写了 "这个例子是为了指出你在每个函数中得到的 arguments 集合。每个函数都可以将它的参数作为集合获取,并且可以相应地执行许多操作。”。已经有一个链接(请参阅蓝色文本?),您可以点击该链接以了解有关arguments 的更多信息。
  • 空字符串和 0 也被评估为 false,因此在第二个示例中,您无法通过调用 val(0) 设置值
  • @RupeshPatel,这是link for arguments
【解决方案2】:

只需检查函数是否带有参数调用即可完成

function stuff(moreStuff){
   if(typeof moreStuff === "undefined"){
      return originalStuff;
   }else{
      setStuff(moreStuff);
   }
}

【讨论】:

  • 所以JS中没有重载的概念,但我们可以做一些工作,谢谢回复:)
  • 在这个例子中写if(moreStuff === undefined)是安全的,因为moreStuff是一个参数。 stackoverflow.com/questions/4725603
【解决方案3】:

很简单,只要检查变量是否有值即可:

function foo(param) {
    // Method 1
    if (param != null) {
        // Parameter is defined
    } else {
        // No parameter (or null given)
    }

    // Method 2
    if (arguments.length > 0) {
        // At least one argument has been defined
    }
}

【讨论】:

  • +1 表示第二个选项。但是您的 param != null 可能无法按预期工作 - 请参阅 saladwithsteve.com/2008/02/javascript-undefined-vs-null.html
  • this doesn't work null will not match with param if called lie this foo()
  • @techfoobar 我知道这一点,但是在我上面的代码中实现的检查只允许不是undefined 而不是null 的参数。
  • @RupeshPatel 是的,它会的。如果你做foo()param 将是undefined - 并且undefined == null 是真的。
  • @Niko 据我所知 undefined 是类型,null 是对象本身
【解决方案4】:
function foo(value)
{
     if(typeof value != 'undefined')
     {
         // calling foo(2332)
     }
     else
     {
         // foo()
     }
}

【讨论】:

  • 您的参数名称是value,您正在检查yourvar
【解决方案5】:

几乎所有其他人都提到,他们没有重载参数,但在第一个语句中,没有为函数提供参数。但是,在第二个中,已经提供了一个论点。因此,一个简单的检查typeof something == "undefined" 可以很容易地修改和区分不同的结果。

这是构成.val()函数的相关jQuery代码(版本1.8.0):

val: function( value ) {
        var hooks, ret, isFunction,
            elem = this[0];

        if ( !arguments.length ) {
            if ( elem ) {
                hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

                if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
                    return ret;
                }

                ret = elem.value;

                return typeof ret === "string" ?
                    // handle most common string cases
                    ret.replace(rreturn, "") :
                    // handle cases where value is null/undef or number
                    ret == null ? "" : ret;
            }

            return;
        }

        isFunction = jQuery.isFunction( value );

        return this.each(function( i ) {
            var val,
                self = jQuery(this);

            if ( this.nodeType !== 1 ) {
                return;
            }

            if ( isFunction ) {
                val = value.call( this, i, self.val() );
            } else {
                val = value;
            }

            // Treat null/undefined as ""; convert numbers to string
            if ( val == null ) {
                val = "";
            } else if ( typeof val === "number" ) {
                val += "";
            } else if ( jQuery.isArray( val ) ) {
                val = jQuery.map(val, function ( value ) {
                    return value == null ? "" : value + "";
                });
            }

            hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

            // If set returns undefined, fall back to normal setting
            if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
                this.value = val;
            }
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多