构造函数应在开头校验参数:检查必需参数是否为null/undefined(用== null),并验证类型(如typeof !== 'number'),不满足则throw new TypeError中断执行,防止后续错误。

构造函数内部做参数校验并抛出 TypeError,核心是:在函数体开头用条件判断检查参数类型或有效性,不满足就用 throw new TypeError(...) 中断执行。
检查必需参数是否存在且非 null/undefined
JavaScript 中未传参会得到 undefined,常需先排除。避免后续操作报错(如调用 undefined.method())。
- 用严格相等
=== undefined或== null(兼顾null和undefined)判断 - 推荐使用
arguments.length或 ES6 解构默认值配合校验,但构造函数中更倾向显式检查
示例:
<code class="js">function Person(name, age) {<br> if (name == null) {<br> throw new TypeError('Person constructor requires a non-null name');<br> }<br> if (age == null) {<br> throw new TypeError('Person constructor requires a non-null age');<br> }<br> this.name = name;<br> this.age = age;<br>}></code>校验参数类型是否符合预期
用 typeof、Array.isArray()、instanceof 或 Object.prototype.toString.call() 精确判断类型。
-
typeof value === 'string'适合基础类型(string/number/boolean/function/undefined) -
Array.isArray(value)安全检测数组(比value instanceof Array更可靠) - 对对象或自定义类,可用
value instanceof ExpectedClass或value?.constructor === ExpectedClass
示例:
<code class="js">function Rectangle(width, height) {<br> if (typeof width !== 'number' || typeof height !== 'number') {<br> throw new TypeError('Rectangle expects two numbers for width and height');<br> }<br> if (width throw new TypeError('Rectangle dimensions must be positive numbers');<br> }<br> this.width = width;<br> this.height = height;<br>}></code>校验对象参数的结构和必填字段
当构造函数接收配置对象时,需检查对象本身及关键属性。
- 先确认参数是对象且非
null:typeof config === 'object' && config !== null - 再逐个检查必要属性是否存在、类型正确(如
config.url是字符串,config.timeout是数字) - 可封装为复用的校验工具函数,但构造函数内保持逻辑清晰即可
示例:
<code class="js">function ApiClient(config) {<br> if (typeof config !== 'object' || config === null) {<br> throw new TypeError('ApiClient constructor requires a config object');<br> }<br> if (typeof config.url !== 'string' || !config.url.trim()) {<br> throw new TypeError('config.url must be a non-empty string');<br> }<br> if (typeof config.timeout !== 'number' || config.timeout throw new TypeError('config.timeout must be a non-negative number');<br> }<br> this.url = config.url;<br> this.timeout = config.timeout;<br>}></code>配合 class 语法时的写法(ES6+)
使用 class 时,校验逻辑放在 constructor 方法内,行为完全一致。
- 仍建议在赋值前完成所有校验,保证实例处于有效状态
- 可结合私有字段或 getter/setter 做后续防护,但构造阶段校验是第一道防线
示例:
<code class="js">class User {<br> constructor(name, email) {<br> if (typeof name !== 'string' || name.trim() === '') {<br> throw new TypeError('User name must be a non-empty string');<br> }<br> if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {<br> throw new TypeError('User email must be a valid email string');<br> }<br> this.name = name;<br> this.email = email;<br> }<br>}></code>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











