Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript OOP: how to refer to object

Tags:

javascript

oop

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.

like image 343
Patrickdev Avatar asked Jun 09 '26 05:06

Patrickdev


1 Answers

window.onresize = this.resize.bind(this);

If you're supporting older browsers, include the MDN compatibility patch for Function.prototype.bind().


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!