2017-06-14 52 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);