ES6构造函数支持参数默认值,直接在形参列表用=赋值;仅undefined触发默认值,null/0/''等falsy值不触发;class constructor同样适用,且默认值惰性求值;对象参数需配合解构与空对象默认值使用。

ES6 构造函数可以像普通函数一样设置参数默认值,直接在形参列表中用 = 赋值即可。它不是语法糖,而是标准支持的特性,适用于 function 声明和类(class)的构造方法。
普通 function 构造函数设默认值
使用 function 定义的构造函数,参数默认值写法与普通函数完全一致:
- 参数未传或显式传
undefined时,自动采用默认值 - 传
null、''、0、false等“falsy 值”不会触发默认值——只认undefined
示例:
function Person(name = 'Anonymous', age = 18) {
this.name = name;
this.age = age;
}
new Person(); // { name: 'Anonymous', age: 18 }
new Person('Alice'); // { name: 'Alice', age: 18 }
new Person('Bob', 25); // { name: 'Bob', age: 25 }
new Person(undefined, 30); // { name: 'Anonymous', age: 30 }
new Person(null, 30); // { name: null, age: 30 } ← 注意:null 不触发默认
Class 构造器中设默认值
class 的 constructor 本质也是函数,同样支持参数默认值:
- 写法相同:在
constructor(...)的形参中直接赋值 - 默认值表达式是惰性求值的,每次实例化时重新执行(比如可含
Date.now()、Math.random())
示例:
class Button {
constructor(text = 'Click me', type = 'button', id = `btn-${Date.now()}`) {
this.text = text;
this.type = type;
this.id = id;
}
}
new Button(); // { text: 'Click me', type: 'button', id: 'btn-1749511620...' }
new Button('Save'); // { text: 'Save', type: 'button', id: 'btn-...' }
结合解构 + 默认值处理对象参数
当希望接收一个配置对象时,推荐把整个对象设为默认值,再配合解构赋值,避免 undefined 解构报错:
- 错误写法:
constructor({ width, height })—— 不传参数会报错 - 正确写法:
constructor({ width = 100, height = 50 } = {})—— 先给对象设默认空对象,再解构
示例:
class Canvas {
constructor({ width = 800, height = 600, color = '#fff' } = {}) {
this.width = width;
this.height = height;
this.color = color;
}
}
new Canvas(); // 正常:全用默认
new Canvas({ width: 1024 }); // height/color 仍用默认
new Canvas(); // 甚至不传任何参数也安全
注意事项
几个容易踩坑的点:
- 不能重复声明同名参数:
function Foo(x = 1, x) {...}会报SyntaxError - 参数作用域内不能再用
let/const声明同名变量 -
null、0、空字符串等不会被当作“缺失”,默认值不生效;如需覆盖这些情况,得在函数体内手动判断


















