简体   繁体   中英

How to add new properties to class constructor, if there are exist same param names?

I'm trying to make object: Cube { length: 1, surfaceArea: 6, volume: 1 } But it now work because the class have same params. If I delete "set surfaceArea...", constructor works. I need a class, that can assign two parameters, if you have another one. So I stuck at first step. `

class Cube {
  constructor(length) {
    this.length = length;
    this.surfaceArea = length ** 2 * 6;
    this.volume = length ** 3;
  }
  set surfaceArea (value) {

  }
  get surfaceArea () {

  }
  set volume (value) {

  }
  get volume () {

  }
}
var cube = new Cube(1);
console.log(cube)

`

How to build this class.

The problem with what you have is that you have setters that do nothing and getters that do nothing. So this.surfaceArea = ___ is a no-op, and if you read from the surfaceArea property, you'll always get undefined (the implicit return value of the surfaceArea getter). (And both of those are true for volume as well.)

You have to either:

  • Store the values somewhere, or
  • Perform the calcuation in the getters

If you decide to store the values somewhere, you have a couple of options for where to store them: public properties or private fields . You'll also want to make length an accessor property instead of a data property as it is now, because otherwise assigning a different value to length makes your surfaceArea and volume incorrect. (And doing that means you'll need a place to store length , since if the length property itself is an accessor, you nee somewhere else to keep its current value.)

If you decide to do the calculations every time surfaceArea or volume is accessed , remove the setters for them and don't assign to surfaceArea or volume in the constructor (since they're entirely dynamic, derived from length ).

I'm purposefully not including code in this answer because I suspect this is some kind of class assignment or similar where the expectation is that you'll write the code. So instead I'm giving you pointers to how you might do that. More about that here: How do I ask and answer homework questions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM