I have the following JavaScript object. When the window resizes, I want it to call its own resize() method. However, in the window.onresize function, this refers to window – not the Canvas object. How do I call the Canvas object?
function Canvas(element) {
this.element = element;
this.canvas = element.getContext("2d");
this.width = element.width;
this.height = element.height;
this.resize = function () {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.element.width = this.width;
this.element.height = this.height;
};
window.onresize = function () {
this.resize();
^- error
};
}
Thank you in advance.
If you’re supporting older browsers, include the MDN compatibility patch for
Function.prototype.bind().