我正在尝试包装一个为所有 SVGElements 实现的名为 getScreenCTM
的函数。 .
我的目标是所有 svg 元素对此方法的所有调用都将调用我的包装函数,该函数将打印一些内容,然后委托(delegate)给原始的 native 实现。
这是我尝试过的:
<svg id="a"></svg>
和
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();
但是当执行最后一行时,没有打印任何内容。原文getScreenCTM
被调用而不是我的包装器实现。
您可以在这里使用它:https://jsfiddle.net/zwxr2c9k/1/
我怎样才能做到这一点?
最佳答案
您可能扩展了错误的元素,看起来您有一个 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>
另请注意,您不能只调用 window.nativeGetScreenCTM
,因为它要求 this
值是实际的 SVG 元素。
但是,您可以使用 apply
或 call
关于javascript - 如何全局重写 HTMLElement 原生方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946746/