简体   繁体   English

Javascript OOP:如何引用对象

[英]Javascript OOP: how to refer to object

I have the following JavaScript object. 我有以下JavaScript对象。 When the window resizes, I want it to call its own resize() method. 当窗口调整大小时,我希望它调用自己的resize()方法。 However, in the window.onresize function, this refers to window - not the Canvas object. 但是,在window.onresize函数中, this是指window - 而不是Canvas对象。 How do I call the Canvas object? 如何调用Canvas对象?

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. 将值“this”保存在onresize处理程序的闭包中的构造函数范围内。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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