【问题标题】:How to autoincrement id value using es6 js class notation?如何使用 es6 js 类表示法自动增加 id 值?
【发布时间】:2017-06-14 10:56:28
【问题描述】:

我对 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];
        }
    }

【问题讨论】:

    标签: javascript class ecmascript-6


    【解决方案1】:

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

    class Rectangle {
    
      constructor() {
        this._id = Rectangle.incrementId()
      }
    
      static incrementId() {
        if (!this.latestId) this.latestId = 1
        else this.latestId++
        return this.latestId
      }
    }
    

    【讨论】:

    • 谢谢薛西斯!它有效,但我有一些问题,生成器创建 _id = 1 两次 oO
    • 我找到了解决方案: static incrementId() { if (!this.latestId) { this.latestId = 1; } 否则 this.latestId++;返回 this.latestId; }
    • @Alex 我更新了我的答案以反映您发现的问题。问题是返回i++ 而不是++i,因为他们设置了不同的分配。一个在表达式结束之后,另一个在表达式结束之前。如果我的回答有帮助,请考虑将其标记为正确:)
    • 是的!这很有帮助 :) 谢谢 XerxesNoble!
    【解决方案2】:

    使用静态变量,它附加在类而不是实例上:

    class Rectangle {
        static count = 0; // Stores count of number of instances created
        
        constructor() {
            this.id = ++this.constructor.count;  // Pre increment the count then use it
        }
    }
    
    let a = new Rectangle();
    console.log(a.id);  // Prints 1
    let b = new Rectangle();
    console.log(b.id);  // Prints 2

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 2014-05-18
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 2018-12-06
      • 2013-04-27
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多