为什么Angular中puzzleType属性在setTimeout回调内打印为undefined?
问题原因
该问题是典型的this上下文指向错误导致的。当你直接将this.handlePuzzle作为参数传入setTimeout时,handlePuzzle执行时的this已经不再指向当前Angular组件实例,而是指向全局window对象(严格模式下为undefined),因此无法读取到组件上挂载的puzzleType属性。第一个console.log能正常输出,是因为它处在subscribe的箭头函数回调中,箭头函数会继承外层作用域的this,也就是当前组件实例。
解决方案
- 方案1:用箭头函数包裹
handlePuzzle调用(最常用,改动最小)
把原代码里的setTimeout(this.handlePuzzle , 3000);替换为:setTimeout(() => this.handlePuzzle(), 3000); - 方案2:使用
bind方法绑定组件实例到handlePuzzle
替换为:setTimeout(this.handlePuzzle.bind(this), 3000); - 方案3:将
handlePuzzle定义为组件的箭头函数属性,永久绑定this指向
修改handlePuzzle的定义:handlePuzzle = () => { console.log(this.puzzleType); if (this.puzzleType == 'text') { new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{ text: 'hello', delay: 2000, x: 2 }], { fontSize: 25, strokeWidth: 1.5, duration: 5000, color: "black" }); } }
内容的提问来源于stack exchange,提问作者user2570937
相关产品推荐
相关产品推荐

