JavaScript类变量重新分配

时间:2019-09-06 05:58:44

标签: javascript ecmascript-6

我正在创建一个Class实例,有点像下面这样固定在变量重新分配上

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)
   }
  }
}

看起来我需要使用@babel/plugin-proposal-class-properties吗?或将Class更改为函数?我想知道是否有一种方法可以更改Class内部的变量,或者这是一种不好的做法?

3 个答案:

答案 0 :(得分:1)

有多个不匹配的括号,class关键字为大写

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')
   }
}

您可以像这样使用它

let obj = new A();
obj.checkBoolen=true
obj.doSomthing()

答案 1 :(得分:1)

我不会使我的结构像这样,但也许您应该看看。

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);

只需继续单击页面即可。

答案 2 :(得分:0)

你有打字 1-小写类开始 2-检查事件侦听器语法

    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');
   }
  }
}