繁体   English   中英

如何在函数内部调用函数?

[英]How to call function inside function?

var abc = {
    'a': 10,
    'b': 10,
    c: function() {
        //like if I have many many functions in c
        init_a();
        multiple();

        function init_a() {
            abc.a = 30;
        }

        function multiple() {
            alert(abc.a * abc.b);
        }

        function minus() {
            alert(abc.a - abc.b);
        }
        return {
            function myalert() {
                var result = abc.a + abc.b;
                alert(result);
            }
        }
    },
    d: function() {
        abc.c.myalert(); // ???  error??
        abc.c().myalert(); // ??? error??  **it run all functions in c but not just myalert, strange things happening...
    }

}
abc.d();

在函数d中调用“ myalert()”函数的正确语法是什么?

myalert() 函数 是本地abc.c()所以这是不可能的。

您可以让c()返回myalert()

c: function() {
    return function myalert() {
      // whatever
    }
}, d: function() {
    this.c()()
}

请注意,不必命名return function() { .. } ,即return function() { .. }

更新资料

如果要像this.c().myalert()那样调用它,则c()需要直接返回一个对象而不是函数:

c: function() {
    return {
        myalert: function() { ... }
    }
}

更新2

除了声明myalert()之外,您的c()函数现在还包含其他语句。 调用时, init_a()multiple()在返回之前会被调用。

我建议重构您的代码,例如将myalert()移到主对象中:

var abc = {
    a: 10,
    b: 10,
    c: function() { ... }
    myalert: function() { ... }
    d: function() {
        this.myalert();
    }
}

您可以从c返回包含myalert的对象:

var abc = {
    'c': function() {
        return {
            myalert: function() {
                alert('foo');
            }
        };
    },
    'd': function(){
        abc.c().myalert(); // foo
    }
};
abc.d();​

演示: http//jsfiddle.net/g2KEK/

c: function() {
    return {
        myalert : function() {
            // whatever
        }
    }
}, d: function() {
    this.c().myalert()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM