
针对javascript类方法动态调用时`this`上下文丢失导致`map`对象未定义的问题,本教程将详细阐述其成因及解决方案,包括使用`call`、`apply`或`bind`显式绑定`this`。同时,为确保游戏资源如图片正确加载,将强调在页面`load`事件而非`domcontentloaded`事件中初始化依赖图像的逻辑,避免视觉异常。
在开发基于JavaScript的游戏或富客户端应用时,我们经常需要管理大量的资源,特别是图片。将这些资源封装到类中是一种常见的做法,例如为游戏角色创建骨架(Skeleton)类来管理其各个部分的图片(如脸部、左右侧)。然而,在动态加载和分配这些资源时,开发者可能会遇到一些常见的陷阱,如this上下文丢失和资源加载时机不当。本文将深入探讨这些问题及其解决方案。
在JavaScript中,this关键字的指向是动态的,它取决于函数被调用的方式,而非函数被定义的位置。当一个方法作为对象属性被调用时(例如 obj.method()),this会指向 obj。但是,当方法被提取出来单独调用,或者作为回调函数传递时,this的指向可能会发生改变,通常会指向全局对象(在非严格模式下)或undefined(在严格模式下,或作为模块的一部分)。
考虑以下代码片段:
const SelectedSkeleton = eval(character).Skeleton; // 假设 eval(character) 返回一个角色实例 const SelectedFunction = SelectedSkeleton[node]; // 例如 SelectedSkeleton.addLeftSide SelectedFunction(name, Node[name]); // 问题出在这里
这里,SelectedFunction(例如 addLeftSide)被提取出来,作为独立的函数进行调用。当addLeftSide方法内部尝试访问 this.LeftSides 时,由于SelectedFunction不是通过 SelectedSkeleton.addLeftSide() 这种形式调用的,this不再指向SelectedSkeleton实例,而是指向了全局对象或undefined。因此,this.LeftSides就变成了undefined.LeftSides,从而引发Cannot destructure property 'LeftSides' of 'this' as it is undefined的错误。
立即学习“Java免费学习笔记(深入)”;
要解决this上下文丢失的问题,我们需要确保在调用SelectedFunction时,其内部的this始终指向正确的Skeleton实例。有几种方法可以实现这一点:
call()和apply()方法允许我们立即调用一个函数,并显式指定该函数执行时的this值。它们唯一的区别在于传递参数的方式:call()接受一系列参数,而apply()接受一个参数数组。
// 修正后的代码片段
Object.keys(Node).forEach(name => {
const SelectedSkeleton = gameCharacters[character].Skeleton; // 假设 gameCharacters 存储了角色实例
const SelectedFunction = SelectedSkeleton[node];
if (typeof SelectedFunction === 'function') {
// 使用 .call() 显式绑定 this
SelectedFunction.call(SelectedSkeleton, name, Node[name]);
} else {
console.warn(`Method ${node} not found or is not a function on Skeleton.`);
}
});通过SelectedFunction.call(SelectedSkeleton, name, Node[name]),我们强制SelectedFunction在执行时将其this上下文设置为SelectedSkeleton实例,从而正确访问到this.Faces、this.LeftSides等Map对象。
bind()方法会创建一个新函数,这个新函数在被调用时,其this值会被永久绑定到bind()的第一个参数。
// 示例:如果需要在循环外提前绑定 const boundFunction = SelectedFunction.bind(SelectedSkeleton); boundFunction(name, Node[name]);
在循环场景中,直接使用call()或apply()通常更简洁,因为它们在调用时即绑定。bind()更适用于将函数作为回调传递给其他API(如事件监听器)的场景。
在Character类中,this.Skeleton = new Skeleton(this.UpdateCharacter); 这一行也可能存在类似的this绑定问题。虽然在原代码中UpdateCharacter方法没有使用this,但如果它将来需要访问Character实例的属性,this的指向就会错误。
为了确保UpdateCharacter内部的this始终指向Character实例,可以采用以下策略:
class Character {
constructor(name) {
this.name = name;
// ...
this.UpdateCharacter = this.UpdateCharacter.bind(this); // 绑定 this
this.Skeleton = new Skeleton(this.UpdateCharacter);
}
UpdateCharacter(ThisSkeleton) { /* ... */ }
}class Character {
constructor(name) {
this.name = name;
// ...
this.Skeleton = new Skeleton(this.UpdateCharacter);
}
UpdateCharacter = (ThisSkeleton) => {
// 箭头函数会捕获其定义时的 this,即 Character 实例
// console.log(this.name); // 可以安全访问 this.name
}
}推荐使用箭头函数形式,它更简洁且能自然地解决this绑定问题。
除了this上下文问题,资源加载时机也是游戏开发中的一个关键点。
原代码中使用了eval(character)来获取角色实例。eval()函数具有安全风险(执行任意字符串代码)和性能开销,应尽量避免。更推荐的做法是将角色实例存储在一个对象或Map中,并通过键值对访问:
// 假设你有一个存储角色实例的对象
const gameCharacters = {
Someone: new Character('Someone')
};
// 在循环中替换 eval
// const SelectedSkeleton = eval(character).Skeleton; // 避免使用 eval
const SelectedSkeleton = gameCharacters[character].Skeleton; // 安全地获取实例浏览器提供两个主要的事件来指示页面内容的加载状态:
在游戏或任何依赖于图片完整呈现的应用中,如果在DOMContentLoaded事件中尝试使用图片,可能会遇到图片未加载完成或处于加载状态导致显示异常的问题。因此,初始化依赖完整图片资源的逻辑,应在window.onload事件(或监听window对象的load事件)中执行,以确保所有图片资源已加载完毕。
window.addEventListener('load', () => {
// 在这里执行依赖于所有图片加载完成的逻辑
// 例如:初始化角色图片、启动游戏循环等
});以下是整合了this绑定、避免eval以及正确加载时机的优化后代码示例:
// Skeleton 和 Character 类定义保持不变 (Character.UpdateCharacter 建议改为箭头函数或绑定)
class Skeleton {
constructor(updateFunction) {
this.Faces = new Map();
this.LeftSides = new Map();
this.RightSides = new Map();
this.CurrentFace = null;
this.CurrentLeftSide = null;
this.CurrentRightSide = null;
this.Update = updateFunction;
}
addFace(name, src) {
if (this.Faces.has(name)) {
console.warn(`Face ${name} already exists`);
return;
}
const FaceImage = new Image();
FaceImage.src = src;
this.Faces.set(name, FaceImage);
}
addLeftSide(name, src) {
if (this.LeftSides.has(name)) {
console.warn(`Left side ${name} already exists`);
return;
}
const LeftSideImage = new Image();
LeftSideImage.src = src;
this.LeftSides.set(name, LeftSideImage);
}
addRightSide(name, src) {
if (this.RightSides.has(name)) {
console.warn(`Right side ${name} already exists`);
return;
}
const RightSideImage = new Image();
RightSideImage.src = src;
this.RightSides.set(name, RightSideImage);
}
setFace(name) {
if (!this.Faces.has(name)) {
console.warn(`Face ${name} does not exist`);
return;
}
this.CurrentFace = this.Faces.get(name);
this.Update(this);
}
setLeftSide(name) {
if (!this.LeftSides.has(name)) {
console.warn(`Left side ${name} does not exist`);
return;
}
this.CurrentLeftSide = this.LeftSides.get(name);
this.Update(this);
}
setRightSide(name) {
if (!this.RightSides.has(name)) { // 注意:原代码此处条件有误,应为 !this.RightSides.has(name)
console.warn(`Right side ${name} does not exist`);
return;
}
this.CurrentRightSide = this.RightSides.get(name);
this.Update(this);
}
}
class Character {
constructor(name) {
this.name = name;
this.PoseTypes = ['normal', 'side'];
this.Pose = 'normal';
// 确保 UpdateCharacter 的 this 绑定到 Character 实例
this.Skeleton = new Skeleton(this.UpdateCharacter.bind(this));
}
UpdateCharacter(ThisSkeleton) {
// 可以在这里访问 this.name 等 Character 实例属性
console.log(`Character ${this.name} updated with skeleton:`, ThisSkeleton);
}
}
// 资源路径定义
const Assets = '../../assets/';
const Images = `${Assets}images/`;
const CharacterImages = `${Images}images/`;
const CharacterImageDirectory = name => `${CharacterImages}${name}`;
const CharDirectory = CharacterImageDirectory('someone');
// 角色资源配置
const CharachterNodes = {
Someone: {
addLeftSide: {
'stand': `${CharDirectory}/1l.png`,
'up': `${CharDirectory}/2l.png`,
},
addRightSide: {
'stand': `${CharDirectory}/1r.png`,
'up': `${CharDirectory}/2r.png`,
},
addFace: {
'happy': `${CharDirectory}/a.png`,
}
},
};
// 存储角色实例的对象,避免使用 eval
const gameCharacters = {
Someone: new Character('Someone') // 确保角色实例已创建
};
// 监听页面的 'load' 事件,确保所有图片资源加载完毕
window.addEventListener('load', () => {
console.log('All page resources including images have loaded.');
Object.keys(CharachterNodes).forEach(characterName => {
const CharacterNode = CharachterNodes[characterName];
const characterInstance = gameCharacters[characterName]; // 从 gameCharacters 获取角色实例
if (!characterInstance) {
console.error(`Character instance for ${characterName} not found in gameCharacters.`);
return;
}
const SelectedSkeleton = characterInstance.Skeleton;
Object.keys(CharacterNode).forEach(nodeMethodName => {
const Node = CharacterNode[nodeMethodName]; // 例如 'addLeftSide', 'addRightSide', 'addFace'
// 检查方法是否存在且是函数
if (typeof SelectedSkeleton[nodeMethodName] === 'function') {
const SelectedFunction = SelectedSkeleton[nodeMethodName];
Object.keys(Node).forEach(assetName => {
// 关键:使用 .call() 显式绑定 this 到 SelectedSkeleton 实例
SelectedFunction.call(SelectedSkeleton, assetName, Node[assetName]);
});
} else {
console.warn(`Method "${nodeMethodName}" not found or is not a function on Skeleton instance for character "${characterName}".`);
}
});
});
// 此时所有图片资源已加载并分配给 Skeleton,可以安全地设置角色姿态
gameCharacters.Someone.Skeleton.setFace('happy');
gameCharacters.Someone.Skeleton.setLeftSide('stand');
gameCharacters.Someone.Skeleton.setRightSide('stand');
console.log('Character assets loaded and set.');
});在JavaScript中进行面向对象编程和资源管理时,理解this上下文的动态绑定机制至关重要。通过使用call()、apply()或bind()等方法显式绑定this,可以有效避免在动态方法调用中遇到的this丢失问题。同时,为了确保依赖图片等外部资源的逻辑能够正确执行,务必在window.onload事件中进行初始化
以上就是解决JavaScript类中this上下文丢失与图片资源加载时机问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号