Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

closure functions in Javascript, is it possible to access the inner function variables?

Hi,

i'm currently looking over Javascript getting my knowledge up on it, as I'm using PHP as the backend, I thought i would take the opportunity. I came across multiple ways of declaring functions, only today I know that functions are actually objects in JS. (How Confusing)...

However, the closure function came to mind and I couldn't get it out of my head and I had to get some learning in.

my question is, the inner function has access to the any variables, functions that are declared within the outer function. Where as the inner function is private, which can only be changed if the outer function is declared again?

var nameIs = function (myName){
    var surname = function (mySecondName){
        return myName + ' ' + mySecondName;
    }

    return surname;
}

//outer being declared when creating a new instance of the function (object)
var declareName = new nameIs('James');

//the inner function is then declared within the console.log()
console.log(declareName('Jones'));

I cannot think of any other way of accessing the inner function result? Any thoughts?

1 Answer

Don't make it a variable.

function nameIs(myName){
    var surname = function (mySecondName){
        return myName + ' ' + mySecondName;
    }
    return surname;
}
console.log(declareName('James'));
console.log(declareName('Jones'));

Not sure if im doing what your trying to do.