Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
programmieren:javascript:js_function_exists [2021/03/16 08:52] – created jgehrkeprogrammieren:javascript:js_function_exists [2022/12/17 12:28] (current) – external edit 127.0.0.1
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/ein Objekt gibt, welches ans Window Object gehangen ist. Also globale Funktionen. Objekte/Funktionen die mit Const oder Let erzeugt wurden, werden nicht erkannt. Ebenso wenig werden Funktionen innerhalb von Objekten erkannt, als z.b. "meinObjekt.get_var()"
  
 <code javascript> <code javascript>
-const function_exists = function( function_name_string ){+function function_exists ( function_name_string ){
   const check_types = [ "function", "object" ];   const check_types = [ "function", "object" ];
   const type_found  = typeof window[function_name_string];   const type_found  = typeof window[function_name_string];
-  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( 'test_1' ); // => true
 +function_exists( 'test_2' );// => false (da const-Funktionen nicht am Window-Object hängen
 +function_exists( 'test_3' ); // => false
 </code> </code>
  
-Verändert nach folgender Quelle: [[https://stackoverflow.com/questions/1042138/how-to-check-if-function-exists-in-javascript|Stackoverflow Beitrag]]+Verändert nach folgender Quelle: [[https://stackoverflow.com/questions/1042138/how-to-check-if-function-exists-in-javascript|Stackoverflow Beitrag (1)]], [[https://stackoverflow.com/questions/8592047/check-if-a-function-exists-with-its-name-in-a-string|Stackoverflow Beitrag (2)]] und [[https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/includes|MDN » array.includes()]] 
 + 
 +**Alternative wie es underscore.js macht** 
 +Dieser Code ist auch gut, hat jedoch den Nachteil, das ''obj'' existieren muss, ansonsten gibt es einen Fehler. 
 + 
 +<code javascript> 
 +is_function = function( obj ) { 
 +  return !!(obj && obj.constructor && obj.call && obj.apply); 
 +}; 
 +</code>
  
 +Quelle: [[https://stackoverflow.com/questions/5999998/check-if-a-variable-is-of-function-type|Stackoverflow Beitrag (3)]]

Page Tools