Javascript OOP:如何引用对象

时间:2012-02-01 23:26:31

标签: javascript oop

我有以下JavaScript对象。当窗口调整大小时,我希望它调用自己的resize()方法。但是,在window.onresize函数中,this引用window - 而不是Canvas对象。如何调用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
    };
}

提前谢谢。

2 个答案:

答案 0 :(得分:4)

将值'this'保存在onresize处理程序的闭包中的构造函数范围内。

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

答案 1 :(得分:4)

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

如果您支持较旧的浏览器,请为Function.prototype.bind()添加the MDN compatibility patch