Javascript check if function exists

New Page

¿Cómo verificar if a function is defined?

Pregunta

Preguntó hace 11 years, 7 months

Modified 3 years, 6 months ago

Visto 55k times

Esta pregunta muestra el esfuerzo de investigación; it is useful and clear

36

Esta pregunta no muestra ningún esfuerzo de investigación; no está claro o no es util

3

Brand is pregunta.

Mostrar actividad en esta publication.

¿Cómo verificar if a function is defined?

  • javascript
  • jquery

Cuota

Compare un enlace a esta pregunta

Copy link CC BY-SA 2.5

Seguir

Sigue esta pregunta para recibir notifications

requested on March 1, 2011 at 8:00 p.m.

User avatar of Benoit

Benedict Benedict

693 2 2 gold badges 7 7 silver badges 7 7 bronze badges

1

  • I had problems checking the type with the options given below, it was returning a string and not working as expected. I changed typeof var_with_func_name to typeof window[var_with_func_name], and it worked fine.

    –Gardner

    Sep 3, 2014 @ 1:27 PM

Add a comment | 

10 answers10

Ordenado por: Restablecer a predeterminado

Puntaje más alto (predeterminado) Tendencia (los votos recientes cuentan más) Fecha de modificación (más reciente primero) Fecha de creación (el más antiguo primero)

This answer is helpful

51

This answer is not helpful

View activity on this post.

Functions of JavaScript that verify if a function exists.

With jQuery.isFunction() can test a parameter to check if (a) is defined and (b) is the “function” type. Ya que solicitó jQuery, esta función le hará cosquillas.

jQuery.isFunction(YourFunction)

If no desea uses jQuery for the cualquier pattern, there is a basic function based on the code of Idealog that will check if the variable is of type function.

function isFunction(fn){ return typeof fn === ‘function’ }

With veces, ya sabe que es una función y, en aras de la optimización, no encuentra ninguna razón para volver a verificar su tipo, en este caso, aquí hay una función que simplye verifica si variable [possibly una function] está definida

function isDefined(foo){ return typeof(foo) !== ‘undefined’ }

How to use these functions

Use jQuery:

function foo(){} if(jQuery.isFunction(foo)) alert(‘This is a function’);

With cualquiera de las functions Javascript que nos son de jQuery proporcionadas anteriormente. Dependiendo del contexto de uso, estas functions pueden o no ser confiables. Ver más abajo

function foo(){} if(isFunction(foo)) alert(‘is of type function’); if(isDefined(foo)) alert(‘if it’s a function, it’s defined’);

Brand tanto indefinido como usandojQuery.isFunction

if (typeof myfunc !== ‘undefined’ && $.isFunction(myfunc)) { // do something }

Source

¿Is jQuery.isFunction() superior?

Según Kyle Florence jQuery.isFunction() may be superior in other situations. In particular útil en algunos casos extremos cuando se usan métodos jQuery, vea su explicación .

En ciertas situaciones en algunos navegadores, las cosas se devuelven incorrectamente como el tipo de “función”, o las cosas que de hecho son funciones se devuelven como otro tipo. Hay varios casos de prueba que puede ver aquí: https ://github.com/jquery/jque …

Un exemple :

var obj = document.createElement(“objet”);

// Firefox dés que c’est un type de fonction d’obj; // => “fonction”

Gardez à l’esprit qu’il s’agit principalement de cas extrêmes, mais la raison pour laquelle $.isFunction a été créé était simplement d’être positif sur le fait que quelque chose était une fonction (ce qui peut être assez important pour la bibliothèque jQuery elle-même, peut-être pas tant pour votre code).

Thanks patrick dw for flagging Kyles’ article. (Patrick DW deleted his account)

At jQuery.com

Note: As of jQuery 1.3, browser-supplied functions such as alert() and DOM element methods such as getAttribute() are not guaranteed to be detected as functions in browsers such as Internet Explorer.

To share

Share a link to this answer

Copy link CC BY-SA 4.0

Follow

Follow this answer to receive notifications

modified on March 5, 2019 at 2:00 PM

answered on March 1, 2011 at 8:03 PM

Sandwich user avatar

sandwich sandwich

2 250 2 2 gold badges 24 24 silver badges 29 29 bronze badges

2

  • 1

    Since it’s tagged with jQuery, I’ll give it a +1 because jQuery uses a slightly safer way to test a function.

    – user113716

    March 1, 2011 at 8:14 PM

  • 2

    maybe a combination of jquery.isFunction and checking if ‘undefined’ is in place. The source

    – DanielV

    Jul 15, 2015 at 10:00 AM

Add a comment | 

This answer is helpful

17

This answer is not helpful

View activity on this post.

Thereby:

if (typeof myFunc != ‘undefined’) { // Assign myFunc }

Don’t just test it against undefined, which is not a constant and can be reassigned.

To share

Share a link to this answer

Copy link CC BY-SA 2.5

Follow

Follow this answer to receive notifications

answered on March 1, 2011 at 8:03 PM

User avatar of Peter C

Peter C Peter C

6 131 1 1 gold badge 24 24 silver badges 37 37 bronze badges

1

  • This is fine for ensuring that myFunc is defined but it doesn’t verify that myFunc is actually a function.

    – Harlem Squirrel

    March 19, 2019 at 1:22 PM

Add a comment | 

This answer is helpful

seven

This answer is not helpful

View activity on this post.

if (typeof(functionName) == ‘function’) { }

.

To share

Share a link to this answer

Copy link CC BY-SA 2.5

Follow

Follow this answer to receive notifications

modified on March 1, 2011 at 8:05 PM

answered on March 1, 2011 at 8:03 PM

User avatar of Richard Dalton

Richard DaltonRichard Dalton

35.1k 6 6 gold badges 72 72 silver badges 91 91 bronze badges

4

  • It just wants to know if it’s defined, not if it’s a function or not.

    – Peter C.

    March 1, 2011 at 8:04 PM

  • Ok, but maybe he doesn’t want to overwrite it even if it’s just a non-working value.

    – Peter C.

    March 1, 2011 at 8:07 PM

  • @alpha123: The question clearly asks how to check if a function is defined.

    – user113716

    March 1, 2011 at 8:29 PM

  • @alpha123 You’re right but it doesn’t matter if that solved his problem. The answer is valid!

    – Adrian P.

    January 29, 2014 at 2:00 PM

Add a comment | 

This answer is helpful

3

This answer is not helpful

View activity on this post.

typeof return string, so you can use the JavaScript typeof operator to find the type of a JavaScript variable.

if ( typeof(youerFunctionName) === ‘undefined’ ) { console.log(‘undefined’); }

To share

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

modified on January 11, 2017 at 8:29

answered on December 22, 2016 at 8:34 am

User avatar of George C

George C George C

31 3 3 bronze badges

0

Add a comment | 

This answer is helpful

2

This answer is not helpful

View activity on this post.

if (myFunc !== undefined) { // myFunc is defined foo(); }

Where

if (myFunc === undefined) { // myFunc is undefined qux(); }

To share

Share a link to this answer

Copy link CC BY-SA 2.5

Follow

Follow this answer to receive notifications

answered on March 1, 2011 at 8:01 PM

user142019 user142019

seven

  • seven

    undefined is not a constant. Testing against it is dangerous.

    – Peter C.

    March 1, 2011 at 8:04 PM

  • 3

    D’accord alors. A chaque fois avant de l’utiliser : undefined = void(0); mais vous ne devriez pas en avoir besoin car définir la valeur de undefined est tout simplement stupide.

    – utilisateur142019

    1 mars 2011 à 20:07

  • 1

    Restez à l’écart de l’opérateur void, c’est déroutant. Tu dois lire l’homme de Douglas Crockford.

    – Pierre C

    1 mars 2011 à 20:08

  • Je dois cependant vous donner un peu de crédit pour en avoir trouvé une utilisation. 😛

    – Pierre C

    1 mars 2011 à 20:10

  • 1

    Le code qui redéfinit undefined devrait casser.

    – utilisateur113716

    1 mars 2011 à 20:30

 | Afficher 2 autres commentaires

Cette réponse est utile

1

Cette réponse n’est pas utile

Afficher l’activité sur ce post.

if ([fonction] != indéfini) { [faire des choses] }

You can also use jQuery’s isFunction() to check it.

To share

Share a link to this answer

Copy link CC BY-SA 2.5

Follow

Follow this answer to receive notifications

answered on March 1, 2011 at 8:01 PM

RDL User Avatar

RDL RDL

7,797 3 3 gold badges 28 28 silver badges 31 31 bronze badges

Add a comment | 

This answer is helpful

1

This answer is not helpful

View activity on this post.

Suppose your function is called func :

if (func) { // The function is already defined (or at least something is defined there) } else { // The function is not defined }

To share

Share a link to this answer

Copy link CC BY-SA 2.5

Follow

Follow this answer to receive notifications

answered on March 1, 2011 at 8:01 PM

Herms user avatar

Hermes Hermes

36.3k 12 12 gold badges 77 77 silver badges 101 101 bronze badges

3

  • 2

    var function = false; down that

    – user142019

    March 1, 2011 at 8:02 PM

  • false is not a function, so the test is still valid. Of course, if you really wanted to break it, you could do var func = true. But I guess if it’s not a function it won’t be anything, which is probably a safe assumption in most cases where you want to check this sort of thing.

    – Hermes

    March 1, 2011 at 8:03 PM

  • Yes, but the test would show it is undefined, when in fact it is. Maybe it doesn’t want to overwrite it even if it’s just a non-working value.

    – Peter C.

    March 1, 2011 at 8:06 PM

Add a comment | 

This answer is helpful

1

This answer is not helpful

View activity on this post.

try this one

/***********************************/ if(typeof(callback) == ‘function’) /** ******************************/

voici un exemple de travail

Partager

Partager un lien vers cette réponse

Copier le lien CC BY-SA 3.0

Suivre

Suivez cette réponse pour recevoir des notifications

répondu le 1 décembre 2015 à 11:28

Avatar of Muhammad Tahir

Mohammed Tahir Mohammed Tahir

2 159 26 26 insignes d’argent 25 25 insignes de bronze

Ajouter un commentaire | 

Cette réponse est utile

0

Cette réponse n’est pas utile

Afficher l’activité sur ce post.

function test(){} if(typeof test != “undefined”) // la fonction est déjà définie

Partager

Partager un lien vers cette réponse

Copier le lien CC BY-SA 2.5

Suivre

Suivez cette réponse pour recevoir des notifications

répondu le 1 mars 2011 à 20:06

jimmystormig user avatar

jimmystormig jimmystormig

10.6k 1 1 insigne d’or 29 29 insignes d’argent 28 28 insignes de bronze

Ajouter un commentaire | 

Cette réponse est utile

0

Cette réponse n’est pas utile

Afficher l’activité sur ce post.

C’est ce que j’utilise pour vérifier si une fonction est déjà définie :

if ( typeof(myFunc()) === ‘undefined’ ) { console.log(‘myFunc undefined’); } else { console.log(‘myFunc defined’); }

To share

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

answered on June 29, 2016 at 3:58 PM

spacebiker user avatar

space biker space biker

3,667 4 4 gold badges 28 28 silver badges 47 47 bronze badges

Add a comment | 

Your answer

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid…

  • Ask for help, clarification, or respond to other responses.
  • Make statements based on opinion; back them up with references or personal experience.

To obtain more information, consult our consejos sobre cómo escribir excelentes respuestas.

Saved Draft

Draft rejected

Sign up or log in

Sign up with Google

Sign up using Facebook

Sign up using your email and password

Send

Publish by invitation

Number

Email

Requerido, pero nunca mostrado

Post as guest

Last name

E-mail

Required, but never displayed

Publica tu respuesta Desechar

Al hacer clic en “Publicar su respuesta”, accept our service terms, privacy policy and cookie policy

No es la respuesta que estás buscando? Explorar otras preguntas etiquetadas

  • javascript
  • jquery

o haga su propia pregunta.

  • Overflow’s blog
  • Odiamos Scrum and Agile… it’s good for you (Ep. 489)

  • Ethereum finally merged, los semiconductores siguen siendo escasos (Ep. 490)

  • Destacado in Meta
  • Recientes cambios de contrast de color y actualizaciones de accesibilidad

  • ¡Revisor for the border! O una solicitud para mjorar la guía de incorporation para nuevos…

  • Update of colectivos: miembros reconocidos, articles y GitLab

  • ¿Debo explain the solo code answers of other characters?

34 people chatting

JavaScript

21 minutes ago – SuperUberDuper

OTZ63 SXuSR p3J02 DH bov acf1068910df4dd83c2fc3af0255af11 F6rDx i63aC

Tamil iOS, Web and Phonegap Developers

23 hours ago – jafarbtech

Cgm7x Wi9nq

vinculado

50

jQuery isFunction check error “function is not defined”

25

¿Prueba jQuery para saber if an object is a method?

1

Check if function is defined in `jQuery` object

Related

3062

Is there an “exists” function for jQuery?

5437

How can I validate an email address in JavaScript?

7623

How do JavaScript closures work?

8450

How to check if an element is hidden in jQuery?

7476

var function_name = function() {} vs function function_name() {}

7707

How do I redirect to another webpage?

5053

How to check if a checkbox is checked in jQuery?

7413

How to check if a string contains a substring in JavaScript?

10962

How can I remove a specific element from an array?

6444

How to return the response of an asynchronous call?

Preguntas calientes of the red

  • ¿Puedo llevar a mi perro al alojamiento para graduados in el campus?
  • Homotopy type of Diff(ℝP³)
  • ¿How to connect a ducha organizer to the tubería de la ducha?
  • ¿Qué videogame se está jugando en Spiderhead (2022)?
  • ¿Qué means “podrían usarte como semilla” in The Marvelous Land of Oz?
  • Período del propagador de osciladores armónicos cuánticos
  • How to parchear a submarina electrical line
  • ¿Por qué las luces intermitentes de los automóviles parpadean al double de velocidad cuando una luz intermitente se ha quemado?
  • ¿La clave en la que está escrita una pieza afecta la ability de interpretation del piano?
  • Alternativas al diagram de dispersion para la visualization de muestras grandes
  • ¿Puedo trabajar de forma remota para un empleador que no sea de Singapore mientras visito Singapore?
  • ¿Is James Earl Jones the actor that more time ha interpretado al mismo personaje?
  • ¿Cuál es el proceso por el cual la humanidad gana su presciencia-inmunidad en la serie Dune?
  • Found an error in an article published in IEEE Transactions on Industrial Informatics
  • How to define the replacement rule for the internal product of Minkowski
  • ¿Podría survive a bosque de pinos con nevadas todo el año?
  • ¿Debería compartirse la práctica con el público en general con el fin de compartir
  • Audio from Mac Studio Display is choppy
  • ¿Qué estilo de escritura académica permite extensas notas explicativas al pie de página?
  • TeXstudio Macro for cambiar texto a \index{texto}
  • Tratando de identificar una novela de Poul Anderson
  • ¿Puede el Congreso issued a revoked decision of the Corte Suprema?
  • ¿Cómo escribo el símbolo schwa ə si Alt + 0259 no funciona?
  • ¿Qué es más fuerte: una habilidad que se puede usar veces de bonificación de competencencia or una que se puede usar una vez por descanso breve?

Feed of preguntas

Subscribe to an RSS

Feed of preguntas

To subscribe to an RSS feed, copy and follow this URL as an RSS reader.


Video Javascript check if function exists

Related Posts

Free chat room code for my website

Contents1 How to set up a free chat room on the website.2 3 comentarios2.1 Trackbacks/Pingbacks2.2 Submit a Comment Cancel reply3 How to Create a Chat Room Website…

Background image full screen css

Contents1 Cómo – Full Page Image1.1 Example1.2 Example2 CSS background image tamaño tutorial: how to codify a complete page background image3 Perfect Full Page Background Image3.1 Méthode CSS géniale,…

WordPress leverage browser caching

Contents1 Aproveche el almacenamiento in hidden del navegador1.1 Will it works for my website?1.2 Where are plugin options1.3 Some JavaScript files still display under Leverage Browser Caching1.4…

WordPress post to facebook page

Contents1 How to Automatically Post to Facebook from WordPress1.1 Download Now: How to Launch a WordPress Website [Free Guide + Checklist]1.2 1. Create an IFTTT account.1.3 2….

Download images from wordpress media library

Contents1 How to export your WordPress media library1.1 Download maintenant : How to launch a WordPress website [Free Guide + Checklist]1.2 How to export your WordPress media…

WordPress single post template

Contents1 How to Create Custom Unique Post Templates in WordPress2 Post Template Files2.1 author.php2.2 Fecha.php3 Handbook navigation4 How to Create Custom Single Post Templates in WordPress5 Video…