简体   繁体   中英

Javascript variable function method call

I apologise if this has been asked elsewhere, I looked but without knowing the name for what I am doing is, I couldn't find anything.

Anyways, the code is as follows:

function alertTypeOptions(AlertType, AlertOptions) {
    navigator.notification.AlertType(AlertOptions);
}

This code is for a phonegap / cordova application.

The basic idea is that you pass the function a two variables and these are used to execute the appropriate method. Examples of this could be alertTypeOptions('beep', '3') or alertTypeOptions('vibrate', '2000'). This (should) play the default alert tone 3x or vibrate the phone for 2 seconds.

I am currently getting the following error:

02-21 15:36:07.185: E/Web Console(7206): Uncaught TypeError:
Object #<Object> has no method 'AlertType'
at file:///android_asset/www/res/scripts.js:181

Obviously the function is currently just using the alertType variable as written rather than as a variable.

Is there a way to get this to work elegantly? Currently my only thoughts are to use a switch statement with AlertType as the check.

Jack

It looks like you want to access your function using the bracket notation :

navigator.notification[AlertType](AlertOptions);

or rather, if I trust this documentation and if AlertOptions is an array :

navigator.notification[AlertType].apply(navigator, AlertOptions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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