繁体   English   中英

回调中的调用函数在Angular中引发错误

[英]Calling function inside callback throws error in Angular

我使用了具有两个回调函数的Cordova插件

window.plugins.screensize.get(this.screensize_success, this.screensize_error);

接下来,在成功回调中,我这样做:

screensize_success(result)
{
    console.log(result); // <--- works fine
    console.log("##### height: "+result.height); // <--- works fine
    this.get_highest(result); // <--- throws an error
}
get_highest(result)
{
  return Math.max(result.height,result.width);
}

我收到此错误:

未捕获(承诺):TypeError:无法读取null的属性“ get_highest”

我究竟做错了什么?

调用回调时,您将失去this上下文。

解决此问题的最简单方法是将回调绑定this

window.plugins.screensize.get(this.screensize_success.bind(this), this.screensize_error.bind(this));

我个人比较喜欢将函数设置为变量,以便在程序中轻松重用,例如:

var get_highest = function (result)
{
  return Math.max(result.height,result.width);
}

并在没有这个的情况下调用它:

get_highest(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM