2016-05-19 5 views
2

を拡張しながら、ここにある:活字体キャッチされない例外TypeError私はSVGTextElementのための簡単な拡張を作成しようとしています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 Uncaught TypeError: el.setAttribute is not a function

私は間違っていますか?

+0

ここで 'el'は' SVGTextElement'のインスタンスであり、 'setAttribute'というメソッドはありませんが、明らかにこのエラーが発生します。あなたのタイプをチェックするためにtypescriptを使用することを忘れないでください! – iberbeu

答えて

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; 
} 
+1

ありがとう、あなたのアプローチは正常に動作します!私は単純な関数と矢印関数の違いについて知らなかった。 –

関連する問題