我在 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];
}
}
只需在 Rectangle 类中添加一个 ID 生成器作为静态方法即可:
class Rectangle {
constructor() {
this._id = Rectangle.incrementId()
}
static incrementId() {
if (!this.latestId) this.latestId = 1
else this.latestId++
return this.latestId
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)