简体   繁体   中英

How to override default parameter in JavaScript

I've found lots of creative ways to set default parameters in ES5 & ES6 but I have yet to see a simple example of how to override default parameters in JavaScript. Take this example:

new Connection(host, port = 25575, password, timeout = 5000)

The default timeout is fine but the port number is not. When calling this function, JavaScript always treats the second parameter as the password parameter:

myConnection = connFactory.getConnection(process.env.IP,
                                         process.env.PORT,
                                         process.env.PASSWORD)

This code results in an authentication error because the second parameter is assumed to be password . How can I override the default parameter for port without modifying the original function definition?

You may use a config object as a parameter for your function. For example:

function foo({a='SO', b}) {
  console.log(a, b)
}

foo({b: 'Yeap', a: 'baz'}) // baz Yeap
foo({b: 'foo'}) // SO foo

It will guarantee your ordering.

Assuming that 'getConnection' isn't your function but comes from some unreachable for you place, here is one of a few solutions that will guarantee to be working. It is a function which task is to prepare all parameters.

function getConnectionRunner(host, password, optional = {port: 25575, timeout: 5000}) {
  const port = optional.port || 25575;
  const timeout = optional.timeout || 5000;

  connFactory.getConnection(host, port, password, timeout);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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