Javascript 如何使用es6 js类表示法自动增加id值?
我对es6课程有些问题。我需要在每次创建对象时自动增加id值。我真的不明白如何声明变量,给_id赋值,然后递增变量Javascript 如何使用es6 js类表示法自动增加id值?,javascript,class,ecmascript-6,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 =
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];
}
}
只需在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。我找到了解决方案:static incrementId(){if(!this.latestId){this.latestId=1;}否则这个。latestId++;返回这个。latestId;}@Alex我更新了我的答案以反映您发现的问题。问题是返回
i++
而不是++i
,因为它们设置的赋值不同。一个在表达式结束后,另一个在表达式结束前。如果我的答案有帮助,请把它标记为正确的:是的!这是非常有帮助的:)谢谢你XerxesNoble!