Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIFE, javascript, function undefined

Tags:

javascript

This is my IIFE function

var test = function(){
  console.log('fire');
}();

It invokes at start. But how do I call this again?

var fireTestFn = function(){
   test();
}

fireTestFn(); // test() is not a function

JSbin https://jsbin.com/cesuzimogu/edit?js,console

like image 726
Joe Avatar asked Aug 11 '26 02:08

Joe


2 Answers

You could return test from inside using a named function expression.

var test = function fn(){
  console.log('fire');
  return fn;
}();
like image 156
axelduch Avatar answered Aug 12 '26 16:08

axelduch


The result of the IIFE will be assigned to test, which is obviously not a function, because you're not returning a function from the IFEE (or anything for that matter). Keep it simple; what you want is a named function you can call anytime as many times as you want:

function test() {
    console.log('fire');
}
test();  // call as often as you want
like image 27
deceze Avatar answered Aug 12 '26 15:08

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!