简体   繁体   中英

Javascript OOP: how to refer to object

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.

Save the value 'this' in the scope of the constructor in the closure of the onresize handler.

var _this = this;
window.onresize = function () {
    _this.resize();
};
window.onresize = this.resize.bind(this);

如果您支持旧版浏览器,请包含Function.prototype.bind() 的MDN兼容性修补程序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM