node.js 中的默认参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35463985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:56:13  来源:igfitidea点击:

default parameters in node.js

node.jsparameterscallbackdefault

提问by hownowbrowncow

How does one go about setting default parameters in node.js?

如何在 node.js 中设置默认参数?

For instance, let's say I have a function that would normally look like this:

例如,假设我有一个通常如下所示的函数:

function(anInt, aString, cb, aBool=true){
   if(bool){...;}else{...;}
   cb();
}

To call it would look something like this:

调用它看起来像这样:

function(1, 'no', function(){
  ...
}, false);

or:

或者:

function(2, 'yes', function(){
  ...
});

However, it doesn't seem that node.js supports default parameters in this manner. What is the best way to acomplish above?

但是,node.js 似乎不支持这种方式的默认参数。完成上述任务的最佳方法是什么?

采纳答案by Zakkery

Simplest solution is to say inside the function

最简单的解决办法就是在函数里面说

var variable1 = typeof variable1  !== 'undefined' ?  variable1  : default_value;

So this way, if user did not supply variable1, you replace it with default value.

所以这样,如果用户没有提供 variable1,你用默认值替换它。

In your case:

在你的情况下:

function(anInt, aString, cb, aBool) {
  aBool = typeof aBool  !== 'undefined' ? aBool : true;
  if(bool){...;}else{...;}
  cb();
}

回答by mikemaccana

2017 answer: node 6 and above include ES6 default parameters

2017 答案:节点 6 及以上包含 ES6 默认参数

var sayMessage = function(message='This is a default message.') {
  console.log(message);
}

回答by serv-inc

See the github issue. You can enable default parameters in current node versions (f.ex. 5.8.0) by using --harmony_default_parameters

请参阅github 问题。您可以使用以下命令启用当前节点版本(例如 5.8.0)中的默认参数--harmony_default_parameters

node --harmony_default_parameters --eval "const t = function(i = 42) { return i }; console.log(t());"
node --harmony_default_parameters --eval "const t = function(i = 42) { return i }; console.log(t());"

[...]

[...]

It'll be enabled by default in v6.0

它将在 v6.0 中默认启用

回答by Wex

You can use bindto create a new function that already has a set of arguments passed into it:

您可以使用bind来创建一个新函数,该函数已经传递了一组参数:

fn1 = fn.bind(fn, 1, 'no', function(){}, false);
fn1();
fn2 = fn.bind(fn, 2, 'yes', function(){});
fn2(true);

Alternatively, langues like CoffeeScriptthat compile into JavaScript provide mechanisms that support default parameters without having to use bind:

或者,像CoffeeScript这样编译成 JavaScript 的语言提供了支持默认参数的机制,而无需使用bind

CoffeeScript:

fn = (bar='foo') ->


JavaScript:

fn = function(bar) {
  if (bar == null) {
    bar = 'foo';
  }
};