[英]How to override an HTMLElement native method globally?
I am trying to wrap a function that is implemented for all SVGElements called getScreenCTM
. 我试图包装一个为所有SVGElement实现的函数,称为getScreenCTM
。
My goal is that all invocations of this method for all svg elements will invoke my wrapper function that will print something and then delegate to the original, native implementation. 我的目标是,所有svg元素对该方法的所有调用都将调用我的包装函数,该函数将打印一些内容,然后委派给原始的本机实现。
Here is what I tried: 这是我尝试过的:
<svg id="a"></svg>
and 和
window.nativeGetScreenCTM = SVGElement.prototype.getScreenCTM;
SVGElement.prototype.getScreenCTM = function() {
var matrix = window.nativeGetScreenCTM();
console.log('printing something:');
return matrix;
};
var svgElem = document.getElementById('a');
svgElem.getScreenCTM();
but when the last line is executed, nothing is printed. 但是当执行最后一行时,什么也不会打印。 The original getScreenCTM
is invoked instead of my wrapper implementation. 原始的getScreenCTM
代替了我的包装器实现被调用。
You can play with it here: https://jsfiddle.net/zwxr2c9k/1/ 您可以在这里使用它: https : //jsfiddle.net/zwxr2c9k/1/
How can I accomplish this? 我该怎么做?
You're probably extending the wrong element, looks like you have a SVGGraphicsElement
您可能在扩展错误的元素,看起来您有一个SVGGraphicsElement
window.nativeGetScreenCTM = SVGGraphicsElement.prototype.getScreenCTM; SVGGraphicsElement.prototype.getScreenCTM = function() { var matrix = window.nativeGetScreenCTM.apply(this, arguments); console.log('printing something:'); return matrix; }; var svgElem = document.getElementById('a'); svgElem.getScreenCTM();
<svg id="a"></svg>
Also note that you can't just call window.nativeGetScreenCTM
, as it requires the this
value to be an actual SVG element. 还要注意,您不能只调用window.nativeGetScreenCTM
,因为它要求this
值是实际的SVG元素。
You can however call it with apply
or call
但是,您可以使用apply
或call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.