简体   繁体   中英

Invoking a function that is inside an IIFE

I am successfully being able to call a function ( function1 ) which exists outside of an IIFE.

My question is how can I invoke function2 ? Right now it returns function2 is undefined. I am thus sure that this is not the right way to call a function from an IIFE. So I would love to know the correct way and appreciate a brief explanation.

 function function1() { alert('1'); } (function($){ function function2(){ alert('2'); } })(jQuery); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" onkeypress="function1();"/> <input type="text" onkeypress="function2();"/> 

The onkeypress attribute runs in the global context, so it can't see the function inside your IIFE.

Using attributes for event listeners like this is not a recommended practice.

Instead of doing it that way, it's better to attach the event listener from code inside your IIFE, perhaps like this:

 (function($){ function function2(){ alert('2'); } $('#test2').on( 'keypress', function2 ); })(jQuery); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="test2" /> 

I added an id attribute to the input element, but you could also use a class or other ways to identify it when you add the event listener.

Your function is out of scope in the code that you have provided. You could either move function two out of the IIFE or register your event on the inputs inside the IIFE.

 function one() { alert(1) } (function($) { function two() { alert(2) } $('.one').keypress(one) $('.two').keypress(two) })(jQuery) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="one" type="text" /> <input class="two" type="text" /> 

Use jQuery, of course!

 function function1() { console.log('1'); } (function($){ $('input').eq(1).keypress(function function2() { console.log('2'); }) })(jQuery); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" onkeypress="function1();"/> <input type="text"/> 

Yes I'm aware I completely side-stepped the issue.

The point is, you should be doing what is considered good practice, and not trying to force something which is considered bad practice into working.

You can use it if you make function2 public

 function function1() { alert('1'); } var myFuncs = (function($){ function function2(){ alert('2'); } return { fun2:function2 } })(jQuery); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" onkeypress="function1();"/> <input type="text" onkeypress="myFuncs.fun2();"/> 

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