This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
programmieren:javascript:js_function_exists [2021/03/16 08:53] – jgehrke | programmieren:javascript:js_function_exists [2024/05/07 08:50] (current) – jgehrke | ||
---|---|---|---|
Line 2: | Line 2: | ||
Mit diesem Snippet kann man sicher stellen ob eine Funktion existiert oder nicht. Nützlich um ggf. zu vermeiden, dass man Module doppelt registriert. | Mit diesem Snippet kann man sicher stellen ob eine Funktion existiert oder nicht. Nützlich um ggf. zu vermeiden, dass man Module doppelt registriert. | ||
+ | |||
+ | Achtung dieser Code sagt nur ob es eine Funktion/ | ||
<code javascript> | <code javascript> | ||
- | const function_exists = function( function_name_string ){ | + | function |
const check_types = [ " | const check_types = [ " | ||
const type_found | const type_found | ||
- | const is_function = check_types.includes( type_found ); | + | const is_function = check_types.includes( type_found ); // Nicht IE11 kompatibel |
return is_function; | return is_function; | ||
} | } | ||
+ | |||
+ | /* Usage: */ | ||
+ | function test_1(){ / | ||
+ | const test_2 = function(){ /*...*/ } | ||
+ | let test_3 = 1234; | ||
+ | |||
+ | function_exists( ' | ||
+ | function_exists( ' | ||
+ | function_exists( ' | ||
</ | </ | ||
- | Verändert nach folgender Quelle: [[https:// | + | Verändert nach folgender Quelle: [[https:// |
+ | |||
+ | **Alternative wie es underscore.js macht** | ||
+ | Dieser Code ist auch gut und genauer in der Kontrolle, ich bin mir nur nicht sicher ob jede Function auch wirklich einen Constructor und ein Apply hat. | ||
+ | |||
+ | <code javascript> | ||
+ | is_function = function( obj ) { | ||
+ | return !!(obj && obj.constructor && obj.call && obj.apply); | ||
+ | }; | ||
+ | </ | ||
+ | Quelle: [[https:// |