0

I am creating a Class instance, I am kinda stuck on variable reassign, like below

class A {
  constructor() {
    this.checkBoolen = false
  }

  checkBoolen = false // error, asks to install @babel/plugin-proposal-class-properties to get support.

  click() {
   document.addEventListener('click', e => {
      this.checkBoolen=true // <- a class constructor's prototype property can't be reassigned.
   })
  }

  doSomthing() {
   if(this.checkBoolen = true // <- never get there) {
    console.log('do something')
       setTimeout(function(){ this.checkBoolen = false}, 3000)
   }
  }
}

Looks like either I need to use @babel/plugin-proposal-class-properties? or change the Class to a function? I am wondering if there is a way to change variable inside Class or it is a bad practice?

2
  • 1
    Multiple Syntax Errors Commented Sep 6, 2019 at 6:02
  • If you use arrow functions instead of traditional function then it may solve your issue. This is due to scope of variable will be maintained. Commented Sep 6, 2019 at 6:17

3 Answers 3

1

There are multiple mismatch brackets, class keyword is uppercased

class A {
  constructor() {
    this.checkBoolen = false
  }

   checkBoolen = false // error, asks to install @babel/plugin-proposal-class-properties to get support.

  click() {
   document.addEventListener('click', e => {
      this.checkBoolen=true // <- a class constructor's prototype property can't be reassigned.
   });
  }

  doSomthing() {
   if(this.checkBoolen = true )// <- never get there) {
    console.log('do something')
   }
}

And you can use it like this

let obj = new A();
obj.checkBoolen=true
obj.doSomthing()
Sign up to request clarification or add additional context in comments.

Comments

1

I would not make my structure like this, but perhaps you should take a look.

class WTF{
  constructor(clickElement){
    this.clickElement = clickElement; this.checkBool = false;
    clickElement.onclick = e => {
      this.click();
      console.log(this.checkBool);
    }
  }
  click(){
    this.checkBool = !this.checkBool;
    return this;
  }
}
let wtf = new WTF(document);

Just keep clicking on the page.

Comments

0

you have typeo 1- start class with lowercase class 2- check eventlistener syntax

    class D {
  constructor() {
    this.checkBoolen = false;
  }

  checkBoolen = false // error, asks to install @babel/plugin-proposal-class-properties to get support.

  click() {
   document.addEventListener('click', (e) => {
      this.checkBoolen=true; // <- a class constructor's prototype property can't be reassigned.
   });
  }

  doSomthing() {
   if(this.checkBoolen = true ) {
    console.log('do something');
   }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.