如何让函数既能接收命名参数(foo({a: 'hello', b: 'it is me'})
),又能接收位置参数(foo('hello', 'it is me')
)?
我知道可以通过向函数传递一个对象来模拟命名参数:
function foo(options) {
options = options || {};
var a = options.a || 'peanut'; // whatever default value
var b = options.b || 'butter'; // whatever default value
console.log(a, b);
}
// ES6 allows automatic destructuring
function foo({a = 'peanut', b = 'butter'} = {}) {
console.log(a, b);
}
但这不允许我传递位置参数。
我想使用ES6,但ES5的任何东西也可以。
a
也是一个对象,那将会混淆两种情况。有什么想法吗? - AKG