当我从服务中调用函数时,"this"是未定义的 [英] 'this' is undefined when I call a function from my service

查看:62
本文介绍了当我从服务中调用函数时,"this"是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在component page

this.timerSessionService.startTimer(this.finish.bind(this), this.onSynchronice);

好吧,它与this.finish一起使用时很好,但是当我从Service调用onSynchronice时,它仍然可以工作并转到我的component,问题出在我的component上,我尝试调用使用.this在我组件内部的函数,它说:

well, it works great with the this.finish, but when I call onSynchronice from my Service it still works and goes to my component the problem comes when on my component I try to call a function that is inside of my component using .this, it says:

错误错误:未捕获(承诺):TypeError:无法设置未定义的属性"pew"

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'pew' of undefined

这是因为在我的onSynchronice函数上我使用了.this,然后它说它不存在...我该如何解决?

this is because on my onSynchronice function I use .this and then it says it does not exist... how do I fix it?

onSynchronice(pew) {
  console.log(pew["pew"]); //Works perfect
  this.pew= pew; //Crashes because of .this
  this.anyfunction(pew); //It crashes and says the same, anyfunction() does not exist, even if it exists
}

推荐答案

您可以将onSynchronice定义为箭头函数:

You can define onSynchronice as an arrow function:

onSynchronice = (pew) => {
    console.log(pew["pew"]);
    this.pew= pew;
    this.anyfunction(pew);
}

这篇关于当我从服务中调用函数时,"this"是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆