Is it possible to do this without "this" being undefined?:
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.prototype.drawRectGrid = (color = "#fff",traceLen,spaceLen)=>{
console.log(this);//Aquí
}
ctx.drawRectGrid();
<canvas id="canvas"></canvas>
It's that I need this to use the ctx methods inside the prototype function (Where is the comment), but if I try to use this code it doesn't let me modify the ctx object (it says it's undefined), and when I do the same but replacing prototype with __proto__
, shows me in the console that this, is undefined. that is, it does not show me the reference to ctx.
Main mistake:
ctx
it's just an instance of theCanvasRenderingContext2D
. Instead ofctx.prototype.drawRectGrid = (...
doing this:CanvasRenderingContext2D.prototype.drawRectGrid = (
I hope it is useful
You have two errors:
.prototype
.window
.So you could fix it like this: