'Boolean toggle for class method
I know there are similar questions but they do not provide the answer I am looking for. So what I'm trying to do is create a method that will toggle a boolean value.
class Example {
constructor(name) {
this._name = name;
this._booleanExample = true;
}
toggleBoolean() {
this._booleanExample = !this._booleanExample;
}
}
I must not be doing something right though because when I call this method it does not toggle the boolean value.
const exampleOne = new Example('example');
exampleOne.toggleBoolean();
// the output remains true
Update:
Ok, so it must be something wrong with the site that I am using because I just recreated the example code inside VSC and everything works fine. I can assess and retrieve the booleanExample and also toggle it from true to false and vice versa.
Solution 1:[1]
I don't think you need to do this, but you could try using an arrow function for toggleBoolean
to ensure that it's using the class-level this
context.
class Example {
constructor(name) {
this._name = name;
this._booleanExample = true;
}
toggleBoolean = () => {
this._booleanExample = !this._booleanExample;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jered |