-1

While I was trying JSS I need to do something like this:

sampleStyle: {
  width: "50px",
  height: this.width
}

I have tried several things to work around that problem but none of them satisfy my needs. The closest one I came up with:

var rect = {
    width_: undefined,
    height_: undefined,
    set width(w) {
        this.width_ = w
        this.height_ = w
    },
    set height(h) {
        this.width_ = h
        this.height_ = h
    },
    get width() {
        return this.width_
    },
    get height() {
        return this.height_
    }
}

I just want to ask you guys why I am getting this.width as undefined for first example and are there any better way to handle that problem ?

suchcodemuchwow
  • 848
  • 2
  • 9
  • 27

2 Answers2

3

You actually just need one getter / setter:

sampleStyle: {
  width: "50px",
  get height() { return this.width },
  set height(h) { this.width = h; },
}

why I am getting this.width as undefined for first example and are there any better way to handle that problem ?

Cause this is not pointing to the object but to window and that doesnt have a width.

And there are a lot ways, see:

Self-references in object literal declarations

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

At first sample you're trying to get width from global (window) context. You must use getters/setters (there are in second example) to work with your local (object) context.

ymd
  • 682
  • 5
  • 18
  • this refers to object itself in first sample not global – suchcodemuchwow Aug 21 '18 at 15:38
  • 1
    No, you're wrong. Let's try run that: `let sampleStyle = {width: 123, height: this}; console.log(sampleStyle.height)` and you will get `Window` object. – ymd Aug 21 '18 at 15:40
  • wow, is it because width is not declared at the moment i tried to get its value and looks outer scope ? – suchcodemuchwow Aug 21 '18 at 15:42
  • It's because `this` calling in a his context (and his context is global - `window`) - he doens't know about `width` property in called object. ;) – ymd Aug 21 '18 at 15:42