-1

I have a class called SizeHolder that stores a width, height, has a function to return an aspect ratio, as well as some accessor functions. However, it seems that creating new instances of that class overwrites the old one.

I've tried changing my compiler, but I really don't know what I'm doing wrong.

class SizeHolder {
  constructor(w, h) {
    self.w = w;
    self.h = h;
  }
  aspectRatio() {
    return (self.w / self.h);
  }
  getW() {
    return self.w;
  }
  getH() {
    return self.h;
  }
}

var a = new SizeHolder(3111, 1777);
var b = new SizeHolder(5, 7);

console.log(a.getW()); //outputs 5
console.log(b.getW()); //outputs 5

I would expect a.getW() to return 3111, but it instead outputs 5?

GalAbra
  • 4,282
  • 4
  • 18
  • 34
Jake Xia
  • 79
  • 8
  • 8
    change `self` to `this` – depperm Jul 09 '19 at 15:32
  • 2
    `self` is what Python uses; when you use `self` like that here, you're creating `window.self`, essentially a global object. Thus while you do have two instances, `b` overrides all the values stored in `self`. – Chris G Jul 09 '19 at 15:34
  • 1
    [This answer](https://stackoverflow.com/a/49481827/3103891) has a great explanation about the `self` parameter – GalAbra Jul 09 '19 at 15:35
  • https://stackoverflow.com/questions/16875767/difference-between-this-and-self-in-javascript – Get Off My Lawn Jul 09 '19 at 15:36

0 Answers0