[英]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.