Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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.

Thanks

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.