如果变量不是't已传递给函数.这是正确的方式吗

Initializing a variable if it wasn't already passed to the function. Is this the right way?

本文关键字:函数 方式吗 变量 如果      更新时间:2023-09-26

我在遇到的几个脚本中看到了这种约定。如果没有传递给函数,它应该初始化一个空的选项对象:

module.exports = function (opts) {
  // Create empty options if none are passed
  opts = opts || {};
};

但在阅读本文时,我想知道,这不会创建一个全局opts变量吗?在它前面加上var不是更好吗?或者commonjs模块样式会阻止这种情况吗?

变量opts在函数签名中声明为参数。因此,它的作用域是函数。将变量声明为参数的效果与var ..基本相同(另外,它是一个参数)。您只是在为该变量重新分配一个新值。

它不会创建全局变量,因为它已经在函数的作用域中,因为它是函数的参数。

var test = function (opts) {
  // Create empty options if none are passed
  opts = opts || {};
};
test({ "test" : true });
alert(typeof opts); // opts is undefined