如何用使用旧方法的新方法覆盖方法?
How to overwrite a method with a new one which uses the old?
例如,我想创建 CanvasRenderingContext2D.lineTo()
的自定义版本。我做的第一件事是:
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.myLineTo = function(x, y) {
this.lineTo(x + 200, y + 200);
}
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(50, 50);
ctx.stroke();
ctx.closePath();
它奏效了。但如果可能的话,我更愿意替换 lineTo
方法而不是添加 myLineTo
。问题是我需要第一个来创建第二个。
不幸的是,这个:
ctx.lineTo = function(x, y) {
this.lineTo(x + 50, y + 50);
}
加注 InternalError: too much recursion
。有没有办法复制 lineTo
方法并防止这种无限递归?
答案是肯定的,方法如下:
ctxLineTo = ctx.lineTo;
ctx.lineTo = function(x, y) {
ctxLineTo.call(this, x + 50, y + 50);
}
(注意不要使用箭头函数,否则 this
将引用 Window 对象。)
例如,我想创建 CanvasRenderingContext2D.lineTo()
的自定义版本。我做的第一件事是:
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.myLineTo = function(x, y) {
this.lineTo(x + 200, y + 200);
}
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(50, 50);
ctx.stroke();
ctx.closePath();
它奏效了。但如果可能的话,我更愿意替换 lineTo
方法而不是添加 myLineTo
。问题是我需要第一个来创建第二个。
不幸的是,这个:
ctx.lineTo = function(x, y) {
this.lineTo(x + 50, y + 50);
}
加注 InternalError: too much recursion
。有没有办法复制 lineTo
方法并防止这种无限递归?
答案是肯定的,方法如下:
ctxLineTo = ctx.lineTo;
ctx.lineTo = function(x, y) {
ctxLineTo.call(this, x + 50, y + 50);
}
(注意不要使用箭头函数,否则 this
将引用 Window 对象。)