Javascript嵌套函数"不是函数"

时间:2016-11-16 18:50:41

标签: javascript

所以,我有一个javascript文件,包含在我的页面中。以下是它的要点:

var PageTransitions = (function() {

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

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

})();

在页面上,我使用:

PageTransitions.nextPage(x, x, x);

工作正常。但是,尝试使用

PageTransitions.setCurrent(x);

给了我PageTransitions.setCurrent不是函数

不确定为什么会这样,确保语法正确。不幸的是,它是工作的东西,不允许分享它发生的实际页面。如果我们的高级开发人员看一看,但他们说它看起来应该有效。有关为什么会发生这种情况的任何想法?

我在调用javascript文件后调用setCurrent,也尝试在nextPage之后移动它以确定。 nextPage仍然有用,setCurrent仍然不是一个函数。

还尝试重命名setCurrent,并传递它的变量。仍然没有好处。

3 个答案:

答案 0 :(得分:4)

如果您要进行连锁,您将需要属性,而不仅仅是在另一个函数中定义的函数,最简单的是对象文字

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);

或者如果IIFE有目的,则返回对象文字

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

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

答案 1 :(得分:2)

如果PageTransitions正在运行,则不是由于您发送的代码所致。

您需要返回功能,以便var PageTransitions = (function() { function setCurrent(currentSet) { alert(currentSet); } function nextPage(options, direction, gotopage) { //some working code, not important } return { setCurrent: setCurrent, nextPage: nextPage }; })(); 可以访问它:

PageTransitions.setCurrent

现在 String weather = jsonJavaRootObject.get("weather").toString(); 已定义。

答案 2 :(得分:0)

(function() {

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

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

    var o = {};  // Dummy object

    // set properties to local functions
    o.setCurrent = setCurrent; 
    o.nextPage = nextPage;

    // Attach dummy to global namespace to make it available
    window.PageTransitions= o;

})();

// Now, you can access your functions via your namespace:
PageTransitions.setCurrent("test");
PageTransitions.nextPage();