Home > other >  shorthand way to reference `this` propeties?
shorthand way to reference `this` propeties?

Time:02-02

I have a class

class Foo {
  constructor(x, y) {
    this.x = x
    this.y = y
  Bar() {
    console.log(this.x, this.y)
}

I recall seeing a method of referring to this. variables without having to specify this. Something like

class Foo {
  constructor(x,y) {
    this.x = x
    this.y = y
  Bar() {
    x,y = [this] // something like this
    console.log(x, y) // equivalent to this.x, this.y
}

I desire this because I have dozens of statements that call methods on this.ctx - like this.ctx.rect() - and I don't want to have to have this. prepended to all of them for the sake of readability.

Is there a syntax for this?

CodePudding user response:

You can deconstruct this like any JavaScript object,

Bar() {
    const {x, y} = this;
}

I do not recommend doing this however, it seems like it would not scale well as a technique.

CodePudding user response:

Objects (including arrays and functions) are handled by reference, meaning that if you write

let a = this.ctx;

then a points to the same object as ctx and you can do a.rect().

  •  Tags:  
  • Related