简体   繁体   English

nodeJS中的重载函数调用

[英]Overloaded function call in nodeJS

I have two js files add.js and testAdd.js 我有两个js文件add.js和testAdd.js

add.js add.js

module.exports = function add(x,y) {
    console.log("------Starts x+y----");
    var a = x+y;
    console.log(a);
    return a;
}

module.exports = function add(x,y,z) {
    console.log("------Starts x+y+z----");
    var a = x+y+z;
    console.log(a);
    return a;
}

testAdd.js testAdd.js

var add = require('./add');

add(300,100);

add(300,100,233);

From the testAdd I am calling the add method in the add.js 从testAdd我调用add.js中的add方法

What is happening is function call is always going to the add(x,y,z) as function is not selecting based on the parameters(as in java). 发生的事情是函数调用总是转到add(x,y,z),因为函数没有根据参数进行选择(如java中所示)。

I am new to nodeJS. 我是nodeJS的新手。 Can someone help me to understand this flow? 有人能帮我理解这个流程吗? And also help me to fix this issue. 并帮助我解决这个问题。 Thanks in advance. 提前致谢。

Attaching the console o/p:- 连接控制台o / p: -

在此输入图像描述

JavaScript doesn't have function overloading. JavaScript没有函数重载。 If you want to have your function take an optional third argument, you can set a default value (with a recent Node version): 如果您希望函数采用可选的第三个参数,则可以设置默认值(使用最新的Node版本):

function add(x, y, z = 0) {
  ...
}

You can use it with two ( add(300, 100) ) or with three ( add(300, 100, 233) ) arguments. 您可以将它与两个( add(300, 100) )或三个( add(300, 100, 233) )参数一起使用。

If you don't have a recent enough Node version, you have to do some manual validation on the third argument: 如果您没有最新的Node版本,则必须对第三个参数进行一些手动验证:

function add(x, y, z) {
  z = Number.isFinite(z) ? z : 0;
  ...
}

Javascript does not support function overloading. Javascript不支持函数重载。 Although robertklep 's solution is great. 虽然罗伯特克尔普的解决方案很棒。 There is one more way you can use.That is arguments object . 还有一种方法可以使用。这就是参数对象

arguments is very good when you have unknown number of parameters to be passed into the function. 当你要传递给函数的参数数目不详的论点是非常好的。 see more here . 在这里看到更多

Below is how will it look. 下面是它的外观。

//add.js
function add() {
  var args=Array.prototype.slice.call(arguments);
  console.log(arguments);
  console.log(args);
  console.log("------Starts x+y+z+.....and so on----");
  var ans = args.reduce(function(prev,curr){return prev+curr;});
  console.log(ans);
  return ans;
}
var sum = add(1,8,32,4);
module.exports = add;//to make it available outside.

On executing the above.(as node add.js ),The output is as follows. 在执行上述。(作为node add.js )时,输出如下。

{ '0': 1, '1': 8, '2': 32, '3': 4 }
[ 1, 8, 32, 4 ]
------Starts x+y+z+.....and so on----
45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM