简体   繁体   中英

How to get an object properties value while next property is being initialized?

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 ?

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

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.

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