Home > Net >  Typescript: How to change Class Fields Value by Class Function?
Typescript: How to change Class Fields Value by Class Function?

Time:10-25

    class foo {
      data = {};
      show = true;
      cancel = {
        click: function (data?: any) {
          console.log("click cancel", data);
          this.show = false// todo, When i call "myfoo.cancel.click()", how can i change foo.show to false? If not pass myfoo into click() would be better.
        },
      };
    }

    let myfoo = new foo();
    console.log(myfoo.show);
    myfoo.cancel.click();
    console.log(myfoo.show);

output:

true
click cancel undefined
true

When i call myfoo.cancel.click(), how can i change foo.show to false? I hope the output can be:

true
click cancel undefined
false

By the way, after I read How to access the correct this inside a callback, I know should not use this.

If not pass myfoo into cancel.click() would be better. The click function used in many popup components, all the components's cancel button call cancel.click(), so I would not write more for cancel.click().

CodePudding user response:

Change your click function to an arrow function:

class foo {
  data = {};
  show = true;
  cancel = {
    click: (data?: any) => {
      console.log("click cancel", data);
      this.show = false
    },
  };
}

let myfoo = new foo();
console.log(myfoo.show);
myfoo.cancel.click();
console.log(myfoo.show);
  • Related