我正在尝试为SVGTextElement创建一个简单的扩展,这里是:
interface SVGTextElement {
setX(value: string): SVGTextElement;
setY(value: string): SVGTextElement;
}
SVGTextElement.prototype.setX = (value: string): SVGTextElement => {
var el: SVGTextElement = this;
el.setAttribute("x", value);
return el;
}
SVGTextElement.prototype.setY = (value: string): SVGTextElement => {
var el: SVGTextElement = this;
el.setAttribute("y", value);
return el;
}
我正在使用此扩展程序:
const e = document.createElementNS("http://www.w3.org/2000/svg", "text");
e.setX("0");
但我收到错误:
SvgTextElementExtensions.ts:18未捕获的TypeError:el.setAttribute不是函数
我做错了什么?
答案 0 :(得分:1)
你不应该在这里使用胖箭头语法,它会将this
绑定到窗口,而窗口没有setAttribute
。这样做:
SVGTextElement.prototype.setX = function (value: string): SVGTextElement {
var el: SVGTextElement = this;
el.setAttribute("x", value);
return el;
}
SVGTextElement.prototype.setY = function (value: string): SVGTextElement {
var el: SVGTextElement = this;
el.setAttribute("y", value);
return el;
}