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


Bruno Dias
Bruno Dias
10,554 Points

What methods do you know to implement JavaScript encapsulation?

I came across this question few days ago and am wondering if anyone here knows a good method to implement JavaScript encapsulation.

1 Answer

Steven Parker
Steven Parker
230,231 Points

The only method I'm familiar with relies on function scope, where the local variables declared within a function are all private to that function. So if you implement an object with your methods, wrap that along with your variables inside an anonymous function which returns the object, and then assign a variable by invoking the function, you have instantiated an object with fully encapsulated data. The inner object is known as a closure.

Here's a simple example:

var capsule = function() {
    var data = 42;
    return {
        getData: function() {
            return data;
        setData: function(val) {
            data = val;

Now nothing prevents you from accessing something named "capsule.data", but that is not the inner data variable. The real one can only be accessed via capsule.getData() and capsule.setData(n).