简体   繁体   English

ES6获取默认参数/参数

[英]ES6 Get default parameters/arguments

How can I get the value of the default parameters/arguments dynamicly without using the parameter variable? 如何在不使用参数变量的情况下动态获取默认参数/参数的值?

function someFunc(param1 = 'value', param2 = 'value') {
    console.log(arguments.length);
    console.log(arguments[0]);
}

someFunc(); //0 undefined

I wanted to do the same, in order to assign several attributes to the instance of my class. 我想做同样的事情,以便为类的实例分配几个属性。

This approach might not help you since it uses one object argument instead of two arguments, still worth to mention: 这种方法可能对您没有帮助,因为它使用一个对象参数而不是两个参数,仍然值得一提:

class MyClass{
  constructor(params={param1:3.1415, param2:'Hello'}){
    //*assign* effectively destructures the params arg
    Ojbect.assign(this,params);
  }
}

Similarly your example would look like this: 同样,您的示例如下所示:

function someFunc(params = {param1:'value', param2: 'value'}) {
    console.log(Object.keys(params).length);
    console.log(params['param1']);
}

Note that this approach requires your argument to be an object and that given one of the two arguments the other one will not be present in the default object . 请注意,这种方法要求您的参数是一个对象,并且给定两个参数之一,则另一个参数将不会出现在默认对象中

You don't. 你不知道 Think about it this way. 这样想吧。 How do you get the default value with the old method? 如何使用旧方法获取默认值?

function someFunc(param1, param2) {
    param1 = param1 || 'value';
    param2 = param2 || 'value';

    console.log(arguments.length);
    console.log(arguments[0]);
}

someFunc(); //0 undefined

Your best bet is to store the default value in a variable, and compare it in runtime. 最好的选择是将默认值存储在变量中,并在运行时对其进行比较。 But that is kind of pointless. 但这是毫无意义的。

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

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