Angular 2中Cannot read property 'this.text' of undefined报错求助
解决回调中
Cannot read property 'this.text' of undefined错误 我来帮你拆解并解决这个问题,核心是回调函数的this上下文丢失,再加上几处语法/拼写错误共同导致的:
问题分析
this上下文丢失:当你把listenSucess作为回调传递给Speech.listen()时,这个函数的执行上下文不再是Lesson类的实例,严格模式下this会变成undefined,自然无法访问this.text。- 拼写错误:
listenSucess里的reuslt是笔误,应该改为result;Speech.js里的funtion拼写错误,要改成function。 - 语法不完整:
Speech.js中的函数和自执行函数都没有正确闭合括号,会导致代码无法正常运行。
解决方案
1. 修正TypeScript中的this绑定问题
有两种常用方法来保留类实例的this上下文:
方法一:使用箭头函数定义回调
箭头函数会自动捕获当前类实例的this,不会丢失上下文:
declare var Speech: any; export class Lesson implements OnInit { text = ''; constructor() { this.text = 'hh'; } ToSpeech(){ Speech.listen(this.listenSucess); } // 改用箭头函数定义回调 listenSucess = (result) => { this.text = result; // 这里的this正确指向Lesson实例 } }
方法二:传递回调时用bind(this)绑定上下文
在把listenSucess传给Speech.listen()时,手动绑定当前实例的this:
declare var Speech: any; export class Lesson implements OnInit { text = ''; constructor() { this.text = 'hh'; } ToSpeech(){ // 绑定this到当前Lesson实例 Speech.listen(this.listenSucess.bind(this)); } listenSucess(result){ this.text = result; // 现在this正确指向Lesson实例 } }
2. 修正Speech.js中的语法错误
修复拼写和括号闭合问题:
var Speech= (function () { return { // 修正funtion为function listen:function(success){ window.plugins.speechRecognition.startListening(function (result) { success(result); }); // 补上闭合括号 } } })(); // 补上自执行函数的闭合括号
3. 修复拼写错误
一定要把listenSucess里的reuslt改成正确的result,否则会出现新的变量未定义错误。
内容的提问来源于stack exchange,提问作者Kiến Trần Trung
相关产品推荐
相关产品推荐

