如何使用es6 js类表示法自动增加id值?

Ale*_*lex 3 javascript class ecmascript-6

我在es6中的类有一些问题.每次我创建对象时,我都需要自动增量id值.真的不明白我怎么能声明变量,给_id赋值然后增加增量变量.

    class Rectangle {

        constructor(name,width,height,x,y) {
            if (typeof(name) === 'string' && typeof(width,height,x,y) === 'number' ) {  
                this._id = ?;
                this._name = name;
                this._width = width;
                this._height = height;
                this._x = x;
                this._y = y;

                var div = document.createElement("div");
                document.body.appendChild(div);                 
                div.id = this._id;
                div.style.width = this._width + "px";
                div.style.height = this._height + "px";
                div.style.backgroundColor = "#ededed";
                div.innerHTML = name;


            }

            else  {
                alert("No way!");
                return false;
            }


        }

        moveObj(dx,dy) {
            this._x = this._x + dx
            this._y = this._y + dy
            console.log(this._x,this._y)
            return this;
        }

        getCoords() {
            let x = this._x;
            let y = this._y;
            return [x,y];
        }
    }
Run Code Online (Sandbox Code Playgroud)

xno*_*xno 8

只需在Rectangle类中添加一个ID生成器作为静态方法:

class Rectangle {

  constructor() {
    this._id = Rectangle.incrementId()
  }

  static incrementId() {
    if (!this.latestId) this.latestId = 1
    else this.latestId++
    return this.latestId
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我找到了解决方案: staticincrementId() { if (!this.latestId) { this.latestId = 1; 否则 this.latestId++; 返回 this.latestId; } (2认同)