gpt4 book ai didi

Javascript OOP : how to refer to object

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:12 25 4
gpt4 key购买 nike

我有以下 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
};
}

提前谢谢你。

最佳答案

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

如果您支持旧版浏览器,请包含 the MDN compatibility patch对于 Function.prototype.bind()

关于Javascript OOP : how to refer to object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com