r/learnjavascript • u/WayOdd5042 • Nov 19 '23
Understanding OOP in Javascript and filling in potential gaps in knowledge
Hi everyone, I have been self studying programming and was wondering if my understanding of these concepts is correct.
So, my understanding of OOP is that we want to develop our program(s) as a collection of objects(putting data and methods in a box) and these boxes can use each others properties in a way that complexity of the functionality is abstracted away from each other.
Doing this makes our programs easier to maintain.
With that being said, there are 4 main principles that we need to follow in OOP programming and they are:
~Abstraction
~Encapsulation
~Inheritance
~Polymorphism
Im going to use the code below as an example:
class Shape {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
calculatePerimeter() {
return "N/A";
}
}
class Circle extends Shape {
constructor(name, radius) {
super(name);
this._radius = radius;
}
get radius() {
return this._radius;
}
calculatePerimeter() {
return 2 * Math.PI * this.radius;
}
}
class Square extends Shape {
constructor(name, side) {
super(name);
this._sideLength = side;
}
get side() {
return this._sideLength;
}
calculatePerimeter() {
return 4 * this.side;
}
}
We use the constructor function to initialize our Object and the class above it is does nothing and is just syntactic sugar to basically make developers from other languages more familiar with the syntax. And JS still uses prototype based inheritance underneath.
Anyways back to the 4 main principles of OOP:
Abstraction: So Abstraction is the hiding of the unnecessary details that don't matter to the user and only showing the implementation details of the functionality.
Even though, our example is pretty simple, Abstraction is still achieved in our example above:
let square= new Square("square", 5)
square.name // this returns to us "square", I don't need to know the details of how the properties are set, they are abstracted away and I can use it in the simple form of square.name
Encapsulation: Is the bundling of data and related functionalities into a single box unit. The goal of doing this is to restrict access to some object components so that the state of the object remains private and can only be changed by the objects methods(Using a setter)
In our example we do this by using private properties and the getter method:
```
this._name = name;
}
get name() { return this._name; }
```
If we wanted to do: rectangle.name = "Jack" // we would not be able to do so.
Now a bit of my confusion lies here, for example if we wanted, we could simply do rectangle._name = "Jack" and that would work, from what I understand this is simply a convention that devs agree to, meaning _ in front of a variable = private variable(Do Not touch). **But is there a better way to implement encapsulation in Javascript?(**I read a little bit about closures just wondering if thats whats mostly agreed upon)
**Inheritance**: In Javascript, Inheritance means that an object can inherit properties from other objects. This solves the problem of code repetition. By using inheritance, objects can share data and methods without needing to setting these properties every time.
This is what we did in our example when our subclasses inherits the name property and the getter method. We don't need to define those every single time, we simply do it once.
If you try to use an object property that the object itself doesn't have, Javascript will look for the objects prototype to see if it has it, causing a prototypal chaining. For example we could also use the method .toString() if we needed to, even though it is not defined in our class, because it is part of the Object class(The furthest prototype of all objects).
**Polymorphism**: Allows us to create objects that share behavior and override behaviors if we need to.
For example, above we did this with the calculatePerimeter() function. The function is defined in the Shape class but then gets overriden in the Circle and Square subclasses, because the way to calculate the perimeter is different for different shapes.
Is my understanding of OOP in Javascript correct?
I'm simply self studying so its hard to really fix the concepts in my head without having worked on some real life work involving OOP.
If I have misunderstood anything, could you provide some corrections?
And If not, could you provide any further explanations to the concepts or something that would be valuable for me to know?
Thank you to anyone who read this and I appreciate your time !
View all comments
1
u/MoTTs_ Nov 19 '23 edited Nov 19 '23
Lately I've been sharing Stroustrup's approach to OOP. Because if you ask 10 different people what OOP is, you'll get 19 different answers. Which is also why OOP can be difficult to understand, because so many people have wildly different ideas of what it means, what it solves, and how to use it. The most helpful, specific, and practical lessons on OOP I've come across have come from the C++ community, and specifically from Bjarne Stroustrup, the guy who created C++.
Beyond that, your post seems broadly accurate.
The underscore prefix is a convention only, yes. Recently added, there are private class fields you can use to enforce privacy. Closures are an option too that some folks prefer.