DEV Community

Daniel Wilder
Daniel Wilder

Posted on

Object Oriented JavaScript

The Problem

When creating dynamic web apps, JavaScript is an amazing tool which enables us to write functions that can be used to manipulate the DOM and handle client-server interactions. However, as our web apps grow in size, these functions can quickly get meshed together in a complicated web, leaving more room for bugs and code which is generally harder to read and change. It's very likely that as our web apps grow in size we will be dealing with dozens, if not hundreds of HTML elements. In turn, our DOM manipulation will quickly become messy. Luckily for us, there is a way to structure our code in a way that changes the layout from a web of free-standing functions to a structure or collection of components or cells. This way of organizing our code is known as Object Oriented Programming.

Object Oriented Programmin: An Overview:

In object oriented programming, our code is separated into containers. These containers are composed pf data, information, variables as well as behaviors we define pertaining to the information. Object oriented programming gives us structure. It establishes the relationship between our data and the functions that define the behavior. We structure our code in a way where we instantiate data that inherits behavioral properties we define in the class the object is associated with. Benefits of organizing our code in such a way include:

  • Our code becomes easier to change. There is a clear place to add/remove code.
  • We can design our code in a way that the behavioral functions we define only interact with the data they are supposed to.
  • Our code is easier to replicate. When an object is created with unique data, the instance methods we define in the class operate in such a way that is unique to that object.
  • Our code becomes easier to read by adding more organization.

In Practice

On a high level, this makes sense. Let's take a look at how object oriented JavaScript differs from purely functional JavaScript. Here is some functional javascript:

let model = "Honda Civic";
let mileage = 50000;

function goVroom(typeOfCar){
  console.log(`${model} goes vrooooom!!`})
};

function howOldIsMyCar(mileage){
  console.log(`my car has ${mileage} miles.`)
};

function driveToSanDiego(mileage){
  return mileage + 1000;
}

goVroom(model);
//=> Honda Civic goes vrooooom!!

howOldIsMyCar(mileage);
//=> my car has 50000 miles.

mileage = driveToSanDiego(mileage);
howOldIsMyCar(mileage);
//=> my car has 51000 miles.



This code works and we can tell it is related to behaviors and attributes of a car. However, there is nothing that structurally relates this code.
If we were to write the previous code in an object oriented way, it would encode the relationship of the data and behavioral methods. That code would look something like this:

class Car {
 constructor(model, mileage){
  this.model = model;
  this.mileage = mileage;
  }

  goVroom(model) {
   console.log(`{this.model} goes vrooooom!!`);
  }

  howOldIsMyCar(mileage) { 
   console.log(`My car has ${mileage} miles.`);
  }

  driveToSanDiego(mileage){
   this.mileage += 1000; 
  }

}

let jalopy = Car.new("astro", 150000);

jalopy
//=> Car {model: "astro", mileage:150000};

jalopy.goVroom()
//=> astro goes vrooooom!!

jalopy.howOldIsMyCar()
//=> My car has 150000 miles.

jalopy.driveToSanDiego()

jalopy
//=> Car {model: "astro", mileage:160000};

Here the Car object is a class or the structure for all of JavaScript object oriented programming. We create an instance of this class, in this case it's jalopy. This takes in two arguments: model and mileage.The instance methods we defined have access to the data using the keyword this. This refers to the instance or specific object associated with the class. Our code now has structure and methods associated for specific instances of data. Neat!

Conclusion
Object oriented programming is a powerful way to organize our code and allow specific instances of related data to share behavioral functions. We have gone over how it is not only good practice to keep this when working with our models and the backend but with the frontend as well, using the class object constructor provided to us by JavaScript.

Top comments (9)

Collapse
 
madza profile image
Madza • Edited

For smaller projects OOP could be a bit of overkill, but for mid-size and larger apps where complexity kicks in, its spot on.

No wonder companies mainly go OOP, as it ensures higher level of re-usability, scalability, code-redundancy and maintenance options.

*There's a typo, (fix typeOfCar to model) in goVroom function.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
madza profile image
Madza

It's a mixture between ability to identify the most appropriate tools for specific tasks and personal preferences. To me, OOP happens to be where it's at cause of massive amount of CRUD systems in corporate world.

Collapse
 
jwp profile image
John Peters • Edited

No mention of inheritance was made. What was shown was merely a class definition with methods.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
jwp profile image
John Peters • Edited

Actually this is a terminology war. Your definition of OOP is that it cannot contain the perfectly legitimate ECMA compliant Class. The reason, you say, is because it's internal implementation uses the prototype inheritance
(PI) system. Which you refer to as inheritance and call 'syntactic sugar'.

Nonsense. The word inheritance alone, as used above does not mean PI. Google and 25 years of OOP show that clearly. Besides OOP folks don't favor inheritance, they favor composition, just like Javascript does.

Besides all OOP winds up at small reusable functions anyway. It's much cleaner and easier to use the class than writing out verbose PI statements for properties.

Making a statement like 'not good for small projects' in my mind, is only a Javascript centric way of thinking. Using the Class construct is legit and ultimately has zero run time performance effects. For many OOP centric people it's a preferred choice. Besides sugar in any form is sweet.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
jwp profile image
John Peters • Edited

JavaScript classes are not classes in the traditional OOP sense

Internals aside there's little difference in how they behave in JavaScript and C# for example.

I'm not sure I understand what you mean.

JavaScript folks freely mix the words OOP and Inheritance when 1) They really know little about OOP and 2) They really mean Protypal Inheritance which is not the traditional meaning of the word Inheritance.

Debatable.

If you are seeing anyone favor inheritance over composition then you are working with junior level developers.

There is no problem with using the class construct in JavaScript.

The whole point of my replies. Plenty of folks will prefer the simplicity of using the Class over (PI). I'm one of them

I'm not really defensive, just willing to challenge absolute statements that are not universally true.

Collapse
 
theuserll profile image
L.L. • Edited

Great example and well explained. Thanks :)