ES6 - 如何声明隐式类成员?

时间:2018-05-05 14:14:16

标签: javascript ecmascript-6 phpstorm jsdoc

如果类成员是从某些选项创建的,那么如何声明它们?

import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'timer',
  templateUrl: './timer.component.html',
  styleUrls: ['./timer.component.scss']
})
export class TimerComponent implements OnInit {

  private timeString : string;
  private duration = 5;
  private seconds = "--";
  private minutes = "--";   
  private clockDisplay : string;
  private interval: number;

  constructor() { }

  ngOnInit() {
    this.tickTick(121)
  }

  tickTick(duration) {
    this.duration = duration
    if (this.duration > 0) {
      this.interval = window.setInterval(() => {
        this.duration = this.duration - 1
        if (this.duration <= 0) {
          clearInterval(this.interval)
        }
        if (this.duration % 60 < 10) {
          this.seconds = "0" + this.duration % 60
        } else {
          this.seconds = (this.duration % 60).toString()
        }

        if (this.duration / 60 < 10) {
          this.minutes = "0" + parseInt("" + this.duration / 60, 10)
        } else {
          this.minutes = "" + parseInt((this.duration / 60).toString(), 10)
        }

        this.clockDisplay = this.minutes + " : " + this.seconds;

        if(this.minutes === '00' && this.seconds === '00'){
          // I want send event when minutes and seconds == 0
        }

        document.body.innerHTML = this.clockDisplay
      }, 1000);
    }
  }

}

3 个答案:

答案 0 :(得分:3)

如果您使用的是Babel,则可以改为使用class property

class cls {
    arr = []
    constructor(options) {
        Object.assign(this, options);
        this.arr[0] = 1;
    }
}

答案 1 :(得分:3)

为了使IDE(Jetbrains PhpStorm / WebStorm)无法识别显式定义的类属性,可以使用JSDoc指定成员:

class cls {
    /**
     @name cls#arr
     @type Array
     */

    constructor(options) {...}
}

由于使用Object.assign分配属性并不能提供额外的好处,更自然的方法是在this上明确定义属性(如其他答案所述)。

在ES6中:

class cls {
   constructor(options) {
        this.arr = [];

        Object.assign(this, options);

        this.arr[0] = 1;
    }
}

在带有class field proposal的ES.next中,需要在Babel中预设第3阶段(或更低版本):

class cls {
   arr = [];

   constructor(options) {
        Object.assign(this, options);

        this.arr[0] = 1;
    }
}

在构造函数体之前计算类字段,ES.next选项是ES6选项的语法糖。这两个选项是相同的,并由IDE识别。

答案 2 :(得分:2)

不要使用Object.assign来创建具有默认值的属性。写

class cls {
    constructor(options) {
        this.arr = [];
        Object.assign(this, options);
        this.arr[0] = 1; // should work now
    }
}