类函数未返回预期值:未传参未触发错误仅获environment属性
问题分析与解决
核心问题
你遇到的情况是:未传入参数实例化Space类时,没触发预期的错误,反而能直接拿到environment属性。根源在于两点:
- 构造函数无论是否传入参数,都会把
settings.environment赋值给实例的environment属性,只要实例化类就能直接访问这个属性。 - 错误判断逻辑仅存在于
create方法中,只有调用该方法才会触发错误返回,若未调用则不会看到预期错误。
另外代码还有隐藏问题:直接修改require引入的settings对象,Node.js会缓存模块内容,这会导致后续其他地方使用settings时拿到被修改后的值,造成全局污染。
修复方案
方案1:构造阶段直接校验参数(实例化时报错)
如果希望创建Space实例时必须传入参数,把校验逻辑移到构造函数中,直接抛出错误:
const settings = require("../../settings.json") class Space{ constructor(length, width, height){ // 构造时校验参数,缺失直接抛出错误 if(length == undefined || width == undefined || height == undefined){ throw new Error("Missing element!") } this.width = width this.height = height this.length = length // 拷贝原environment,避免意外修改原settings对象 this.environment = [...settings.environment] } create(){ const spaceVolume = this.height * this.width * this.length // 返回新配置对象,不修改原settings return { ...settings, environment: [ {...this.environment[0], space: spaceVolume}, {...this.environment[1], objects: true} ] } } } module.exports = Space
方案2:保留create方法校验,确保调用它获取结果
如果仍想在调用create时才校验,必须确保通过调用create方法获取结果,而非直接访问实例的environment,同时修复全局污染问题:
const settings = require("../../settings.json") class Space{ constructor(length, width, height){ this.width = width this.height = height this.length = length this.environment = [...settings.environment] } create(){ if(this.length == undefined || this.width == undefined || this.height == undefined){ return { error : "Missing element!" } } else { const spaceVolume = this.height * this.width * this.length // 返回新配置对象,不修改原settings return { ...settings, environment: [ {...this.environment[0], space: spaceVolume}, {...this.environment[1], objects: true} ] } } } } module.exports = Space
使用时必须调用create方法:
const Space = require('./Space') const space = new Space() const result = space.create() console.log(result) // 此时会返回{ error: "Missing element!" }
内容的提问来源于stack exchange,提问作者reichkansler
相关产品推荐
相关产品推荐

