JavaScript Function Overloading

原创转载请注明出处:http://agilestyle.iteye.com/blog/2341742

 

Function Overloading

A function signature is made up of the function name plus the number and type of parameters the function expects. JavaScript functions can accept any number of parameters, and the types of parameters a function takes aren’t specified at all. That means JavaScript functions don’t actually have signatures. A lack of function signatures also means a lack of function overloading. For example:

function sayMessage(message) {
    console.log(message);
}

function sayMessage() {
    console.log("Default message");
}

sayMessage("Hello!");       // outputs "Default message"

 

In JavaScript when you define multiple functions with the same name, the one that appears last in your code wins.The earlier function declarations are completely removed, and the last is the one that is used. Once again, it helps to think about this situation using objects:

var sayMessage = new Function("message", "console.log(message);");
sayMessage = new Function("console.log(\"Default message\");");
sayMessage("Hello!");       // outputs "Default message"

 

Looking at the code this way makes it clear why the previous code didn't work. A function object is being assigned to sayMessage twice in a row, so it makes sense that the first function object would be lost.

The fact that functions don't have signatures in JavaScript doesn't mean you can't mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do. For example:

function sayMessage(message) {
    if (arguments.length === 0) {
        message = "Default message";
    }
    console.log(message);
}
sayMessage("Hello!");       // outputs "Hello!"

Note:

In practice, checking the named parameter against undefined is more common than relying on arguments.length

 

Reference

Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值