我正在创建一个使用 SVG 圆圈可视化的对象(客户(,因此我想在客户对象中引用此 SVG 圆圈。
我试图做一些聪明的事情:
class Customer {
constructor(color, queue) {
this.color = color;
this.queue = queue;
this.id = Date.now();
this.queue.push(this)
this.circle = { ...document.createElementNS("http://www.w3.org/2000/svg", "circle"), queue.newLocation(), {fill: this.color, id: this.id} };
}
}
queue.newLocation()
返回一个{cx: .., cy: ..}
对象。但是我得到的错误是:
Unexpected token '.' (queue`.`newLocation)
当我省略queue.newLocation
时,我得到:
Unexpected token '{'
出了什么问题?
(错误出现在 Chrome 和 Safari 中(。
您应该将 spread 运算符与queue.newLocation()
和{fill: this.color, id: this.id}
一起使用,因为 circle 变量是对象。 表示仅接受键和值。
class Customer {
constructor(color, queue) {
this.color = color;
this.queue = queue;
this.id = Date.now();
this.queue.push(this)
this.circle = { ...document.createElementNS("http://www.w3.org/2000/svg", "circle"), ...queue.newLocation(), ...{fill: this.color, id: this.id} };
}
}
这就是为什么写一行通常不是一个好主意。错误是:
this.circle = { ...document.createElementNS("http://www.w3.org/2000/svg", circle"), queue.newLocation(), {fill: this.color, id: this.id} };
|
|
scroll to see my ASCII arrow pointing to the syntax error -----------------------------------------'
您的点差运营商根本没有错。错误在其他地方。
如果你要把代码写成:
this.circle = {
...document.createElementNS("http://www.w3.org/2000/svg", circle"),
{
fill: this.color,
id: this.id
}
};
然后会发生两件事之一。
第一种可能性是你立即意识到对象{ fill, id}
缺少键,或者它首先不应该是一个对象。因此,正确的代码应如下所示:
this.circle = {
...document.createElementNS("http://www.w3.org/2000/svg", circle"),
attr: { // or something appropriate
fill: this.color,
id: this.id
}
};
或者这个:
this.circle = {
...document.createElementNS("http://www.w3.org/2000/svg", circle"),
fill: this.color,
id: this.id
};
第二种可能性是你没有发现错误,javascript会告诉你错误的行号是queue.newLocation()
之后的{
,这将使错误对你来说很明显。