Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoincrement id value using es6 js class notation?

I have some problem with classes in es6. Me need auto increment id value each time I'm creating objects. Really don't understand how I can declare variable, assign value to _id and then increment increment variable.

    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];
        }
    }
like image 768
Alex Avatar asked Dec 15 '22 01:12

Alex


1 Answers

Just add a ID generator as a static method in the Rectangle class:

class Rectangle {

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

  static incrementId() {
    if (!this.latestId) this.latestId = 1
    else this.latestId++
    return this.latestId
  }
}
like image 161
xno Avatar answered Mar 08 '23 01:03

xno