gpt4 book ai didi

javascript - 原型(prototype) "this"不工作 (JS)

转载 作者:行者123 更新时间:2023-11-29 20:15:18 26 4
gpt4 key购买 nike

尝试使用 Image() 对象执行 .onload 方法,显然它没有继承其函数中的“this”。有帮助吗?

function UI() {
this.canvas_obj = document.getElementById('game');
this.canvas = this.canvas_obj.getContext('2d');
this.imgcache = {};
this.imglist = [
'rooms/main-square.png'
];
for (var i = 0; i < this.imglist.length ; i++) {
var img = new Image();
img.src = this.imglist[i];
this.imgcache[this.imglist[i]] = img;
}
}

// snip //

/*
* drawImg
* Draws an image on the canvas at the specified x, y (if the image isn't in the pre-cache, it creates it as well)
* @param str image path
* @param array x,y
* @param array width, height
*/
UI.prototype.drawImg = function(path, coords, size) {
var found = false;
if (size == undefined) {
var w = 0;
var h = 0;
} else {
var w = size[0];
var h = size[1];
}
for (var i = 0; i < this.imgcache.length ; i++) {
if (path == this.imgcache[i].src) {
found = true;
}
}
if (!found) {
var img = new Image();
img.src = path;
this.imgcache[path] = img;
}
if (w == 0 && h == 0) {
this.imgcache[path].onload = function() {
this.canvas.drawImage(this.imgcache[path], coords[0], coords[1], this.imgcache[path].width, this.imgcache[path].height);
};
} else {
this.imgcache[path].onload = function() {
this.canvas.drawImage(this.imgcache[path], coords[0], coords[1], w, h);
};
}
}

最佳答案

对于每个变量,在 JavaScript 中,this 的范围是相对于你所在的函数的。所以,当在

this.imgcache[path].onload = function() {
// ...
};

this 将绑定(bind)到对象 imgcache[path]。一种常见的方法是将 this 的值保存在另一个变量中(按照惯例,它通常是 that)以便在嵌套函数中访问它:它被称为 closure .

var that = this;

this.imgcache[path].onload = function() {
// that will reference the "outer this"
};

现在,这是由于 JavaScript 如何在函数调用时绑定(bind) this 值。可以使用 callthis 绑定(bind)到另一个值或 apply .

关于javascript - 原型(prototype) "this"不工作 (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342533/

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