Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: How to change Class Fields Value by Class Function?

    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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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().

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading