首页 > 解决方案 > this.init 不是函数

问题描述

我正在为班级做这个,他们的测试说我的构造函数没有被初始化,所以我查了一下发现this.init()。现在我得到“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
  this.init()
}

标签: javascriptconstructorinitialization

解决方案


仅仅是您没有创建构造函数的新实例吗?

此外,volumeandsurfaceArea都是函数,需要调用。

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();

}

const a = new CuboidMaker(1, 2, 3);
console.log(a);


推荐阅读