如何全局覆盖 HTMLElement 本机方法?
How to override an HTMLElement native method globally?
我正在尝试包装为所有 SVGElements 实现的函数,称为 getScreenCTM
。
我的目标是所有 svg 元素对此方法的所有调用都将调用我的包装函数,该函数将打印一些内容,然后委托给原始的本机实现。
这是我尝试过的:
<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
来调用它
我正在尝试包装为所有 SVGElements 实现的函数,称为 getScreenCTM
。
我的目标是所有 svg 元素对此方法的所有调用都将调用我的包装函数,该函数将打印一些内容,然后委托给原始的本机实现。
这是我尝试过的:
<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