JS构造函数调用this.init()报this.init is not a function错误如何解决
报错原因
你遇到的this.init() is not a function报错的核心原因是:你没有在构造函数或其原型链上定义名为init的方法,直接调用不存在的方法自然会触发该错误。
你现在写的CuboidMaker构造函数内部,只给实例挂载了length、width、height三个属性,以及volume、surfaceArea两个方法,全程没有定义init相关的逻辑,所以this.init本身就是undefined,调用时就会报错。
解决方法
你提到测试提示“构造函数未初始化”大概率是你理解错了提示含义,你当前的代码里已经完成了所有实例属性、方法的挂载逻辑,不需要额外的初始化方法,直接删掉最后一行的this.init()调用即可。
修改后可正常运行的代码如下:
function CuboidMaker(length, width, height){ const volume = () => { return this.length * this.width * this.height } const surfaceArea = () => { return 2 * (this.length * this.width + this.length * this.height + this.width * this.height) } this.length = length this.width = width this.height = height this.volume = volume this.surfaceArea = surfaceArea }
如果你确实需要单独抽离初始化逻辑,可以自行补充init方法的定义,示例如下:
function CuboidMaker(length, width, height){ // 先定义init方法 this.init = () => { this.length = length this.width = width this.height = height } const volume = () => { return this.length * this.width * this.height } const surfaceArea = () => { return 2 * (this.length * this.width + this.length * this.height + this.width * this.height) } this.volume = volume this.surfaceArea = surfaceArea // 此时调用init才会正常执行 this.init() }
内容的提问来源于stack exchange,提问作者Cheyenne Bowman
相关产品推荐
相关产品推荐

