可选参数

可选参数

在 js 里,声明一个函数可以定制多个参数,与此同时,你在调用该函数的时候不需要传入所有的参数,它就能正常执行,只不过这些参数默认就是undefined而已。所以似乎 js 的函数天生就带有可选参数这个功能,只不过在你不进行定制的时候它们都具有一个 "统一" 的值罢了。
但,我们也知道,除非函数里就实现了针对某个参数为undefined时的行为,让参数为undefined是比较危险的。
该如何实现函数内的可选参数,我们将用 js 里的构造方法来举例(假如我们要实现一个 Person 类):

function Id(name, age, tel) {
    this.name = name;
    this.age = age;
    this.height = height;
    this.weight = weight;
}

通常我们都会这么实现,现在假想我们要将heightweight参数设为可选参数,可选参数的实质就是令未被赋值的参数具有一个默认值,直白地处理,我们可以写成这样:

function Person(name, age, height, weight) {
    var nHeight = height || 0;
    var nWeight = weight || 0; 
    this.name = name; this.age = age; this.height = nHeight ; this.weight = nWeight ; } 

但是因为我们这里的参数只是简单的赋值给属性,所以我们可以这么写:

function Person(name, age, height, weight) {
    this.name = name;
    this.age = age;
    this.height = height || 0;
    this.weight = weight || 0; } 

面对这样的实现,不难发现它还有点问题——这种实现永远只能把可选参数连续地声明在函数的末端,必要的参数必须得放前面,因为它只能这样生成:

var person = new Person("Turtle", 23);

假如我是ageweight为可选参数呢?

function Person(name, age, height, weight) {
    this.name = name;
    this.age = age || 0;
    this.height = height;
    this.weight = weight || 0; } // 我就不能这样生成Person对象了 var person = new Person("Turtle", "170cm"); 

因为这样子赋值,没法让170cm赋到height属性上,只会赋到age属性上,这显然不是我们想要的。

一种简便的解决方法是不定义这么多的参数赋值,而统一使用一个对象来进行赋值:

function Person(options) {
    this.name = options.name;
    this.age = options.age || 0; this.height = options.height; this.weight = options.weight || 0; } var options = { name: "Turtle", height: "170cm", }; var person = new Person(options); //or var person2 = new Person({ name: "Turtle", height: "170cm", }); 

而在 es6 里,它支持了为参数提供默认值,所以你可以这么干:

 
function Person({name, age = 0, height, weight = 0} = {}) { this.name = name; this.age = age; this.height = height; this.weight = weight; } // 效果和上面一致

猜你喜欢

转载自www.cnblogs.com/aioverg/p/11400641.html