Cormor
Cormor

Reputation: 69

How to overwrite a method with a new one which uses the old?

For example, I wanted to create a custom version of CanvasRenderingContext2D.lineTo(). The first thing I did was:

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();

and it worked. But I would prefer, if possible, to replace the lineTo method instead of adding myLineTo. The problem is that I need the first to create the second.

Unfortunately, this:

ctx.lineTo = function(x, y) {
  this.lineTo(x + 50, y + 50);
}

raises InternalError: too much recursion. Is there a way to copy the lineTo method and prevent this infinite recursion?

Upvotes: 0

Views: 61

Answers (1)

Cormor
Cormor

Reputation: 69

The answer is yes, here is how:

ctxLineTo = ctx.lineTo;
ctx.lineTo = function(x, y) {
  ctxLineTo.call(this, x + 50, y + 50);
}

(Be careful not to use an arrow function or else this will refer to the Window object.)

Upvotes: 1

Related Questions