2017-01-29 1 views
1

私はes6のクラスにいくつか問題があります。私はオブジェクトを作成するたびに自動インクリメントID値が必要です。本当に変数を宣言して_idに値を代入し、インクリメント変数をインクリメントする方法を理解できません。es6 jsクラス表記法を使って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]; 
     } 
    } 

答えて

5

ただ、Rectangleクラスの静的メソッドとしてIDジェネレータを追加します。

class Rectangle { 

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

    static incrementId() { 
    if (!this.latestId) this.latestId = 1 
    else this.latestId++ 
    return this.latestId 
    } 
} 
+0

はあなたにクセルクセスをありがとう!それは動作しますが、私はそのジェネレータが作成するいくつかの問題を抱えている_id = 1回オブジェクト指向 – Alex

+1

私が見つけた解決策:(!this.latestId) 静的incrementId(){ \t場合{ \t \t this.latestId = 1; \t} \t else this.latestId ++; \t return this.latestId; } – Alex

+0

@Alexあなたが見つけた問題を反映するために私の答えを更新しました。問題は、割り当てを別々に設定するときに '++ i'の代わりに' i ++'を返すことでした。 1つは式が終了した後で、もう1つは前のものです。私の答えが助けられたら、それを正しいものとしてマークすることを検討してください:) – XerxesNoble

関連する問題