Cómo saber si una función JavaScript está definida


¿Cómo saber si una función en JavaScript está definida?

Quiero hacer algo como esto

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

Pero me da un

La devolución de llamada no es una función

Error cuando la devolución de llamada no está definida.

Author: Peter Mortensen, 2008-09-17

19 answers

typeof callback === "function"
 401
Author: Tom Ritter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-07 13:14:51

Todas las respuestas actuales usan una cadena literal, que prefiero no tener en mi código si es posible-esto no lo hace (y proporciona un valioso significado semántico, para arrancar):

function isFunction(possibleFunction) {
  return typeof(possibleFunction) === typeof(Function);
}

Personalmente, trato de reducir el número de cadenas que cuelgan en mi código...


También, aunque soy consciente de que typeof es un operador y no una función, hay poco daño en el uso de sintaxis que lo hace aparecer como el último.

 223
Author: Jason Bunting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-10 19:58:07
if (callback && typeof(callback) == "function")

Tenga en cuenta que la devolución de llamada (por sí misma) evalúa a false si es undefined, null, 0, o false. Comparar con null es demasiado específico.

 13
Author: Robin like the bird,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-03 21:50:36

Nuevo en JavaScript No estoy seguro de si el comportamiento ha cambiado, pero la solución dada por Jason Bunting (hace 6 años) no funcionará si no se define la función posible.

function isFunction(possibleFunction) {
  return (typeof(possibleFunction) == typeof(Function));
}

Esto lanzará un error ReferenceError: possibleFunction is not defined mientras el motor intenta resolver la función de símbolo posible (como se menciona en los comentarios a la respuesta de Jason)

Para evitar este comportamiento solo puede pasar el nombre de la función que desea comprobar si existe. So

var possibleFunction = possibleFunction || {};
if (!isFunction(possibleFunction)) return false;

Esto establece que una variable sea función que desea comprobar o el objeto vacío si no está definido y así evita los problemas mencionados anteriormente.

 6
Author: NectarSoft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-29 16:47:26

Esos métodos para saber si se implementa una función también fallan si la variable no está definida, por lo que estamos usando algo más poderoso que admite recibir una cadena:

function isFunctionDefined(functionName) {
    if(eval("typeof(" + functionName + ") == typeof(Function)")) {
        return true;
    }
}

if (isFunctionDefined('myFunction')) {
    myFunction(foo);
}
 5
Author: patriciorocca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-21 16:52:52

Intenta:

if (typeof(callback) == 'function')
 5
Author: bdukes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-08 18:12:08
function something_cool(text, callback){
    alert(text);
    if(typeof(callback)=='function'){ 
        callback(); 
    };
}
 3
Author: ConroyP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-17 17:59:42
if ('function' === typeof callback) ...
 3
Author: Andrew Hedges,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-17 22:50:31
typeof(callback) == "function"
 3
Author: dashtinejad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 09:57:20

Podría hacer

try{
    callback();
}catch(e){};

Sé que hay una respuesta aceptada, pero nadie sugirió esto. No estoy muy seguro de si esto encaja en la descripción de idiomatic, pero funciona para todos los casos.

En los motores JavaScript más nuevos se puede usar un finally en su lugar.

 3
Author: Quentin Engles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-11 13:27:31

Prueba esto:

callback instanceof Function
 2
Author: eWolf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-25 05:30:06

Si miras la fuente de la biblioteca @Venkat Sudheer Reddy Aedama mencionada, underscorejs, puedes ver esto:

_.isFunction = function(obj) {
  return typeof obj == 'function' || false;
};

Esto es solo mi PISTA, PISTA respuesta: >

 2
Author: VentyCZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-16 21:15:38

Intenta:

if (!(typeof(callback)=='undefined')) {...}
 2
Author: Brian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-08 18:12:19

Estaba buscando cómo verificar si una función jQuery estaba definida y no la encontré fácilmente.

Tal vez podría necesitarlo;)

if(typeof jQuery.fn.datepicker !== "undefined")
 1
Author: miguelmpn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-04 14:51:51

Si usa http://underscorejs.org , usted tiene: http://underscorejs.org/#isFunction

_.isFunction(callback);
 0
Author: Venkat Sudheer Reddy Aedama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-28 21:01:46

Si el callback() que está llamando no solo por una vez en una función, podría inicializar el argumento para reutilizar:

callback = (typeof callback === "function") ? callback : function(){};

Por ejemplo:

function something_cool(text, callback) {
    // Initialize arguments
    callback = (typeof callback === "function") ? callback : function(){};

    alert(text);

    if (text==='waitAnotherAJAX') {
        anotherAJAX(callback);
    } else {
        callback();
    }
}

La limitación es que siempre ejecutará el argumento callback aunque no esté definido.

 0
Author: Nick Tsai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-14 10:02:39

Para funciones globales puede usar esta en lugar de eval sugerida en una de las respuestas.

var global = (function (){
    return this;
})();

if (typeof(global.f) != "function")
    global.f = function f1_shim (){
        // commonly used by polyfill libs
    };

También puedes usar global.f instanceof Function, pero afaik. el valor de Function será diferente en diferentes marcos, por lo que solo funcionará correctamente con una sola aplicación de marco. Es por eso que solemos usar typeof en su lugar. Tenga en cuenta que en algunos entornos puede haber anomalías con typeof f también, por ejemplo, por MSIE 6-8 algunas de las funciones por ejemplo alert tenían tipo "objeto".

Por local funciones puede utilizar la de la respuesta aceptada. También puede probar si la función es local o global.

if (typeof(f) == "function")
    if (global.f === f)
        console.log("f is a global function");
    else
        console.log("f is a local function");

Para responder a la pregunta, el código de ejemplo está funcionando para mí sin error en los últimos navegadores, por lo que no estoy seguro de cuál fue el problema con él:

function something_cool(text, callback) {
    alert(text);
    if( callback != null ) callback();
}

Nota: Usaría callback !== undefined en lugar de callback != null, pero hacen casi lo mismo.

 0
Author: inf3rno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-14 10:31:45

La mayoría, si no todas las respuestas anteriores, tienen efectos secundarios para invocar la función

Aquí las mejores prácticas

Tienes función

function myFunction() {
        var x=1;
    }
forma directa de probarlo

//direct way
        if( (typeof window.myFunction)=='function')
            alert('myFunction is function')
        else
            alert('myFunction is not defined');
usar una cadena para que solo pueda tener un lugar para definir el nombre de la función

//byString
        var strFunctionName='myFunction'
        if( (typeof window[strFunctionName])=='function')
            alert(s+' is function');
        else
            alert(s+' is not defined');
 0
Author: TexWiller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-20 06:46:08

Solución de una línea:

function something_cool(text, callback){
    callback && callback();
}
 -1
Author: Samir Alajmovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-18 20:08:50