admin管理员组

文章数量:1418411

I have something like this:

var yourNamespace = {

    foo: function() {
        .....
    },

    bar: function() {
        function foobar() {....
        }
    }
};

Is there a possibility to call inside of foo, the foobar function inside of bar?

I have something like this:

var yourNamespace = {

    foo: function() {
        .....
    },

    bar: function() {
        function foobar() {....
        }
    }
};

Is there a possibility to call inside of foo, the foobar function inside of bar?

Share Improve this question edited Jul 13, 2015 at 13:39 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 13, 2015 at 13:38 Jakub JuszczakJakub Juszczak 7,9174 gold badges22 silver badges41 bronze badges 2
  • 1 No. The function called "foobar" is local to the function assigned to the "bar" property. Unless other code in the "bar" outer function exposes the "foobar" function somehow, then it's private and cannot be accessed from outside "bar". – Pointy Commented Jul 13, 2015 at 13:40
  • The short answer is no. But if you explain a little on what you're trying to achieve, we may be able to give you some good suggestions. – light Commented Jul 13, 2015 at 13:43
Add a ment  | 

2 Answers 2

Reset to default 2

With your exact structure you cannot however you can do something like that :

var yourNamespace = {
   foo: function() {
        ..... 
        yourNamespace.foobar()
    },
    bar: function() {
       function foobar() {....}
       yourNamespace.foobar = foobar;
    }
};

Or nicer, (IMO) :

var yourNamespace = {
   foo: function() {
        ..... 
        yourNamespace.bar.foobar()
    },
    bar: function() {
       yourNamespace.bar.foobar =  function() {....}

    }
};

Please note: in both case, bar() must run before foo() otherwise foobar is undefined

This is just a simple Module pattern. What you should do is make bar it's own module, and return foobar from that module. Example:

var yourNamespace = {

    foo: function() {
        this.bar.foobar();
    },

    bar: {
        abc: '',
        foobar: function() {
            console.log('do something');
        }
    }
};

Or you could do something more like this:

var yourNamespace = {
    foo: function() {
        var bar = this.bar();
    },
    bar: function() {
        var abc = '';
        function foobar() {
            console.log('return abc or do something else');
            return abc;
        }
        return {
            foobar: foobar
        }
    }
};

本文标签: How to call a javascript function inside another functionStack Overflow