Ryan Deming Ryan Deming - 21 days ago 6
Javascript Question

Javascript nested function "not a function"

So, I have a javascript file I'm including in my page. Here's the gist of it:

var PageTransitions = (function() {

function setCurrent(currentSet) {
alert(currentSet);
}

function nextPage(options, direction, gotopage) {
//some working code, not important
}

})();


On the page, I'm using:

PageTransitions.nextPage(x, x, x);


That works fine. However, trying to use

PageTransitions.setCurrent(x);


gives me PageTransitions.setCurrent is not a function

Not sure why this is happening, pretty sure the syntax is correct. Unfortunately it's something for work, not allowed to share the actual page where it's occurring. Had our senior dev take a look, but they said it looked like it should be working. Any thoughts on why this would be happening?

I'm calling setCurrent after the javascript file gets called, also tried moving it after nextPage to be sure. nextPage still worked, setCurrent still not a function.

Also tried renaming setCurrent, and the variable it's being passed. Still no good.

Answer

If you're going to chain, you'll need properties, not just functions defined inside another function, the simplest is an object literal

var PageTransitions = {
    setCurrent : function(currentSet) {
        alert(currentSet);
        return this;
    },
    nextPage : function(options, direction, gotopage) {
        //some working code, not important
        return this;
    }
}

PageTransitions.nextPage(x, x, x);

or if the IIFE has a purpose, returning an object literal

var PageTransitions = (function() {
    function setCurrent(currentSet) { ... }
    function nextPage(options, direction, gotopage) { ... }

    return {setCurrent, nextPage};
})();