简体   繁体   中英

IIFE, javascript, function undefined

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

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

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

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

As the error says

test() is not a function

When you self-invoked the function, the result was stored into test .

In order to be able to use test as a function and call repeatedly elsewhere, do not self-invoke

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

or have the function return an inner function

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

test is not a function, it is undefined . As you haven't returned anything from the anonymous function, undefined will be returned by default. So, when you call test() you get error

TypeError: test is not a function

The IIFE should be enclosed within parentheses () .

  1. You need to wrap your anonymous function in () to make it IIFE
  2. You need to return a function from it so that test will be that function

Demo

 var test = (function() { return function() { document.write('fire'); }; }()); var fireTestFn = function() { test(); } fireTestFn(); 

Something like this will work

var myNamespace = {};

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

    /*ns.myOtherFunction = function(var1) { }*/
})(myNamespace);

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

fireTestFn();

See example here: https://jsbin.com/helumoveqe/edit?js,console

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