0

I am using jQuery and I am a beginner. I have this structure:

function a(){
   function b(){
     return x;
   }
}

I want to return x from primary function that is a(). How can I do this?

5
  • Just return function's b value Commented May 6, 2014 at 11:10
  • You just call b() in a's body. Commented May 6, 2014 at 11:10
  • 1
    FYI, this has nothing to do with jQuery Commented May 6, 2014 at 11:14
  • @A.Wolff: that's right Commented May 6, 2014 at 11:15
  • 1
    @A.Wolff i.sstatic.net/rGtMH.jpg Commented May 6, 2014 at 11:16

6 Answers 6

2

You have a few options.

Assuming:

var x = 1;

You could do this:

// Return a function when calling `a()`, which can be called --> `a()()`;
function a() {
    return function b (){
        return x;
    }
}

a()(); // 1;
// Return the result of `b()` when calling `a()`;
function a(){
    function b(){
        return x;
    }
    return b();
}

a(); // 1;
// Return a object containing a function named `b`.
function a(){
    return {
        b: function(){
            return x;
        }
    };
}

a().b(); // 1;
Sign up to request clarification or add additional context in comments.

Comments

0
function a() {
    return b();
   function b (){

     return x;
   }
}

2 Comments

I guess somebody downvoting everybody's answer here @A.Wolff
@Neel: Looks like it.
0

A cleaner version of answer :

function a(){
    function b(){
        return x;
    }
    return b();
}

Comments

0

Just use:

function a(){
    return b();
}

function b(){
    return x;
}

Comments

0

I think you mean this?

function a() {
    function b (){
        return x;
    }
    return b();
}

Comments

0

Try this fiddle:

function a() {
    var x = 34;
    return function b (){
        return x;
    }
}

var f1 = a();
var f2 = f1();
alert(f2); //34

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.