发布于 2026-01-06 5 阅读
0

命名参数 | JS

命名参数 | JS

今天我再次撰文,想和大家分享一个我前不久发现的实用技巧,我之后在所有使用 JavaScript 的项目中都会用到它。在本文中,我们将了解什么是命名参数,以及它们如何帮助我们编写更简洁的代码。开始吧!


利用 ES6 解构赋值

解构是 ES6 引入的一项功能,它允许我们编写更简洁、更易读的代码。在进入命名参数部分之前,我们将看到一个使用示例。

const food = { tomato: "tomato", banana: "banana" }

// use destructuring for get values, order doesn’t matter
const { banana, tomato } = food

console.log(tomato) // output: "tomato"
Enter fullscreen mode Exit fullscreen mode

标准参数 🆚 命名参数

为了比较两种情况下参数的行为,我们将使用一个名为“createProduct()

标准参数

在这种情况下,我们将以标准方式使用参数,同时还会引入一个名为 ` priceInEurdefault_value` 的参数,其默认值为 `1


/* Create a function with named arguments */
function createProduct(name, priceInEur = 1, weightInKg, heightInCm, widthInCm){
  // functionality
}

// call function and passing args
createProduct('cookies', undefined, 20, 10, 10)
Enter fullscreen mode Exit fullscreen mode

这里我们发现了一个主要缺点,那就是我们需要传递一个undefined值来保持函数中定义的参数顺序,以便它具有默认值。

命名参数

在这个例子中,我们将使用相同的函数,但这次我们将使用命名参数。


/* Create a function with named arguments */
function createProduct({ name, priceInEur = 1, weightInKg, heightInCm, widthInCm }){
  // functionality
}

// call function and passing args
createProduct({
    name: 'cookies',
    //priceInEur | set default value if not passed
    weightInKg: 20,
    heightInCm: 10,
    widthInCm: 10
})

Enter fullscreen mode Exit fullscreen mode

我们可以看到,所谓的命名参数只不过是对对象的键进行解构,在本例中,这些键将作为函数的“参数”。

作为一种对象解构,我们可以利用它的优势,例如省略可选参数、改变对象属性的顺序等等,这些我们稍后会看到。

✅ 优势 ❌ 缺点
参数的顺序无关紧要,因为我们处理的是一个对象。 可能导致创建带有许多参数的函数
无需向 undefined 传递可选参数。 由于需要添加通过参数传递的对象的键和值,代码会变得更长。
提高代码的可扩展性和可维护性
提高易读性
请为你的论点提供更多背景信息

警告

如我们所见,这种做法并不复杂,但也不宜滥用,尤其是在只使用一个参数且函数名称本身就具有描述性的函数中,例如:


 function getProductById(id){
    // code...
}

 function getProductById({ id }){
    // code...
}

Enter fullscreen mode Exit fullscreen mode

(附加内容)在返回值时也采用同样的良好实践

function getProductById(id){
    const response = null, error = null, loading = false

    // code...

    return {
        response,
        error,
        loading
    }
}

// use this way
const { response, error, loading } = getProductById(1)

Enter fullscreen mode Exit fullscreen mode

感谢阅读。😊

谢谢

文章来源:https://dev.to/producthackers/named-arguments-js-2d99