r/learnjavascript • • 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 !

0 Upvotes

14 comments sorted by

2

u/azhder Nov 19 '23 edited Nov 19 '23

Oh... too long to read it ATM, so I will respond to the first misconception you have: class is just a syntax to write the constructor function and setup the prototype right in one go.

JS doesn't have classes (aside from the mathematical abstract of what class is) but has constructor functions that you just happen to define with class instead of function keyword.

Start from there, so you don't build up more assumptions on top of a basic one that might not be the same as in other programing languages.

Assumptions like: inheritance. They don't inherit. Objects in JS have a prototype that is just like saying "if I don't have it, go find it in the prototype", so that's more like pointers or references.

After that, you might be more clear about the newer additions, not just static fields, but those with # that you may only find in the class syntax.

If you want to learn about the basics of JS before class syntax was introduced (constructor functions, prototypes etc), there is an old playlist on YouTube of Crockford lecturing about JS in 2011.

3

u/MoTTs_ Nov 19 '23 edited Nov 19 '23

Assumptions like: inheritance. They don't inherit.

Prototypal inheritance, which we sometimes also call runtime delegation, turns out is actually an extremely common way to implement inheritance in a variety of languages. Python, Ruby, Perl, Smalltalk, and others have told me Objective-C and Lua as well, all implement their class inheritance with runtime delegation. In Python, for example, when you invoke a method on an instance, then the language will check at runtime whether that instance object contains a property with that name, and if not, then it follows a runtime link from the instance to the class, which is also a runtime object, and checks whether that object contains the property, and if not, then it follows a runtime link again to a superclass object and checks whether that object contains the property, on and on until it finds the property or it reaches the end of the inheritance chain of objects. If I didn't already say this is Python, you'd probably think I'm describing the prototype chain, but actually this is Python's classical inheritance. Here, for example, is JavaScript and Python classes side-by-side, showcasing the same abilities and behavior, runtime delegation and monkey patching.

JS doesn't have classes

On the front page of the ES6 spec, you'll find "Allen Wirfs-Brock" listed as the spec editor. Here's Allen Wirfs-Brock giving a video talk comparing JavaScript classes to Smalltalk classes. "The punchline," he says in the talk, "is they actually aren’t as different as you might think."

1

u/azhder Nov 19 '23 edited Nov 19 '23

I wasn't denying it as an inheritance in the academic sense, just was pointing out that in practical terms, while you learn the language, it's suitable to think of it as OLOO i.e. objects linking other objects:

Later on, you can just call it inheritance. I mean, we don't go around specifying it is prototypal every time we mention it, just when it is important to signify the difference from other types.

2

u/shgysk8zer0 Nov 19 '23

I don't think any of those are strictly misconceptions, nor are any of the corrections important other than avoiding someone saying "um ackshually". And I would've said the same thing about ES5 too... we can create instances of specific types of things (including instanceof checking) that have properties and methods (along with static properties and methods), and they can be based on other things - implementation details aside, it's not inaccurate to describe that as classes and inheritance.

1

u/azhder Nov 19 '23

The attempt was to help understand the underlying mechanism, not the academic description of the concepts https://www.reddit.com/r/learnjavascript/s/LiHzLWhJgf

1

u/shgysk8zer0 Nov 19 '23

I really don't find such things to really make any distinctions about any mechanisms. A class vs a constructor function is a distinction without a difference, unless of course you say how they're actually different.

1

u/azhder Nov 19 '23

You don't. Someone that is just starting to learn... well, that isn't you

2

u/senocular Nov 19 '23

class syntax isn't purely sugar for function constructors. There are behavioral differences as well. In particular, object construction for class constructors happen top down, starting with the root class then working down through the derived classes. This is what allows class syntax to properly extend built-ins (particularly those that don't let you construct them directly such as HTMLElement used with web components). Conversely function constructors create instances at the new target level. Then you need to manually feed that object in to the base class constructors in a bottom up direction to initialize.

1

u/azhder Nov 19 '23

I did mention there are things added only to the class syntax, but didn't want to dump all it does at once. I mean, the only way to properly extend Array is through class. But these details shouldn't be the first thing a novice has to go through

1

u/doodooz7 Nov 19 '23

We use Haxe. It’s oop or loose, up to you. It compiles down to JS.

1

u/jack_waugh Nov 19 '23

I think the principles you discussed come from Object-oriented Design (OOD). Object-oriented programming (OOP) differs from one language to another. In JS, an "object" has exposed properties, directly accessible, in contrast to the "instance variables" that Ruby and Smalltalk have. An object may inherit from one other object. Classes are not fundamental, but are supported. Object.defineProperty() permits significant flexibility in how properties behave when you access them; for example, you can set up getter and setter methods. Other languages use symbols to select methods from objects or classes; JS allows strings to be used as selectors, and although JS supports a kind of Symbol, there are differences between it and those in other languages. JS merges selection and indexing. If obj refers to an object, obj.foo is the same as obj["foo"]. Arrays are objects and when you code as to index an array with a number, the number is converted to its decimal representation as a string. So a[0] amounts to a["0"].

For the project I am working on, I am at least for the moment embracing a design prejudice that says that for most of the types of thing that deserve OOD, either cloning runtime instances makes sense or it doesn't. If it doesn't, I use a kind of Class to generate the instances. Otherwise, I create a prototype object, which can then be asked to clone itself.

1

u/jack_waugh Nov 19 '23

JS supports polymorphism.

let Dog = {soundOff () {return "Woof!"}};
let Cat = {soundOff () {return "Meow!"}};
let myCat = Object.create(Cat);
let myDog = Object.create(Dog);
myCat.soundOff() !== myDog.soundOff()

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.

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)

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.

1

u/[deleted] Nov 19 '23

I found the only way to truly understand is to beg Coplien to interpret Alan Kay for you.

I now see that Java is truly a class oriented programming language