2017-06-14 56 views
0

我用一个Cordova plugin其中有两个回调函数:调用函数抛出错误的角度

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); 
} 

我得到这个错误:

Uncaught (in promise): TypeError: Cannot read property 'get_highest' of null

我在做什么错?

回答

2

当呼叫回调被调用时,您将丢失this上下文。

纠正这种

最简单的方法是将回调绑定到this

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

我personnaly希望设置功能变量在你的程序中方便地重复使用,如:

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

和没有这个号码:

get_highest(result);