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


Jason Pallone
Jason Pallone
11,340 Points

What's an example of encapsulation?

So for JavaScript I thought encapsulation was putting a function into a variable, seems I misunderstood. So with OOJS what would an example of encapsulation be, is it just using a method in a object? I'm a little confused honestly.


1 Answer

Hi Jason - Encapsulation is a concept of Object Oriented Programming or OOJS in this case. You're on the right track when you mentioned that it's like using methods in objects - however, it also includes the object's properties/field variables. The idea is that the object's state/property variables and methods are contained (or encapsulated) within the object. For example, I have the following Car class here, with which I can make Car objects:

class Car {
    constructor(name, type){
        this.name = name;
        this.type = type;
    getName() {
        return this.name;
var myCar = new Car('myAwesomeCar', 'race car');

Each car's name name and type properties and functions and encapsulated in the object. Hope that helps!

Jason Pallone
Jason Pallone
11,340 Points

Oh ok that does make sense! So at the end when you said, encapsulated in the object, you mean when we create a new object from the car class, in this case the myCar object? Or the classs car itself?

Encapsulation refers both to the Class and the object made from that class. You can think of the Class as the structure of what an object should look like, it's properties and methods.