JavaScript类Squirrel的jump方法返回undefined,构造函数是否正确?
问题分析与修复
核心问题:方法返回值未输出
你调用squirell1.jump()后没有将返回值打印到控制台,所以看起来像是返回undefined,但实际上jump()方法本身是有正确返回值的。
constructor与类定义的问题
错误抛出TypeError方式
代码中throw TypeError;是抛出构造函数本身,而非TypeError实例,这会导致error.message为空。应该改为抛出实例:throw new TypeError("名称必须为字符串类型"); // color的setter同理修改color setter中的多余return
setter规范上不需要返回值,虽然这不会导致功能问题,但建议移除多余的return:set color(color) { if (typeof color !== "string") { throw new TypeError("颜色必须为字符串类型"); } else { this._color = color; // 去掉不必要的return } }constructor定义是正确的
你的constructor逻辑没问题,通过调用setter(this.name = name和this.color = color)来验证并设置实例属性,符合封装思路。
修复后的完整代码
class Squirrel { constructor(name, color) { this.name = name; this.color = color; } get name() { return this._name; } set name(name) { if (typeof name !== "string") { throw new TypeError("名称必须为字符串类型"); } else { this._name = name; } } get color() { return this._color; } set color(color) { if (typeof color !== "string") { throw new TypeError("颜色必须为字符串类型"); } else { this._color = color; } } jump() { return this._name + " jumping"; } } try { const squirell1 = new Squirrel("noname", "red"); console.log(squirell1.jump()); // 新增console.log输出返回值 } catch (error) { console.log(error.message); }
验证结果
运行修复后的代码,控制台会输出noname jumping,说明jump()方法返回值正常,constructor和类的定义逻辑正确。
内容的提问来源于stack exchange,提问作者Xena
相关产品推荐
相关产品推荐

