Show
Hridoy Banik May 2, 2020 5 min read 1)What is OOP in programming and OOP concept in JavaScriptObject oriented programming is a programming style which breaks the code into segments of objects followed by Class.that can communicate each other.Each object is defined by properties which can be accessible and modified. Free Course Build Apps with Maintainable Code About this CourseThis course is designed to teach web developers how to utilize the various object-oriented programming features within JavaScript. Object-oriented programming allows developers to build applications with reusable and maintainable blocks of code, which leads to efficiency and simplified software design. With object-oriented JavaScript, you'll be able to build classes to construct objects that encapsulate both data and functionality. You'll also learn how to leverage prototypal inheritance to maintain DRY code, allowing you to pass behaviors down to objects. You'll also learn how to keep data safe and secure by creating private state with closures and immediately-invoked function expressions. Course CostFreeTimelineApprox. 3 weeksSkill LevelintermediateIncluded in Product Rich Learning Content Interactive QuizzesTaught by Industry Pros Self-Paced Learning Course LeadsRichard KalehoffInstructor What You Will LearnPrerequisites and RequirementsThis course builds on the skills covered in Intro to JavaScript. Prior to taking this course, the student should be able to:
See the technology requirements for using Udacity. See the Technology Requirements for using Udacity. Why Take This CourseAs a front-end web developer, JavaScript is one of the most important languages in your toolbox. A strong foundation in the language’s features empowers you to build efficient and performant web applications. In this course, you’ll explore a variety of ways to write object-oriented code in JavaScript. You’ll build classes to create new objects that share similar data and functionality. You'll reduce your development time by leveraging JavaScript's prototypal inheritance model, leading to modular and reusable code. And thanks to abstraction and private state, your data will be safe and secure. What do I get?
In my research, I’ve found there are four approaches to Object-Oriented Programming in JavaScript:
Which methods should I use? Which one is “the best” way? Here I’ll present my findings along with information that may help you decide which is right for you. To make that decision, we’re not just going to look at the different flavors but compare conceptual aspects between them: What is Object-Oriented Programming?Object-Oriented Programming is a way of writing code that allows you to create different objects from a common object. The common object is usually called a blueprint while the created objects are called instances. Each instance has properties that are not shared with other instances. For example, if you have a Human blueprint, you can create human instances with different names. The second aspect of Object-Oriented Programming is about structuring code when you have multiple levels of blueprints. This is commonly called Inheritance or subclassing. The third aspect of Object Oriented Programming is about encapsulation where you hide certain pieces of information within the object so they’re not accessible. If you need more than this brief intro, here’s an article that introduces this aspect of Object-Oriented Programming if you need help with it. Let’s begin with the basics — an introduction to the four flavors of Object-Oriented Programming. The four flavors of Object-Oriented ProgrammingThere are four ways to write Object-Oriented Programming in JavaScript. They are: Using Constructor functionsConstructors are functions that contain a
Class syntaxClasses are said to be the “syntactic sugar” of Constructor functions. As in, Classes are an easier way of writing Constructor functions. There’s serious contention about whether Classes are bad (like this and this). We’re not going to dive into those arguments here. Instead, we’re just going to look at how to write code with Classes and decide whether Classes are better than constructors based on the code we write. Classes can be written with the following syntax:
Notice the At first glance, classes seem to be inferior to constructors — there’s more code to write! Hold your horses and don’t form a conclusion at this point. We have a lot more to cover. Classes begin to shine later. As before, you can create an instance with the
Objects Linking to Other Objects (OLOO)OLOO was coined and popularized by Kyle Simpson. In OLOO, you define the blueprint as a normal object. You then use a method (often named
You use
You can chain
Factory functionsFactory functions are functions that return an object. You can return any object. You can even return a Class instance or OLOO instance — and it’ll still be a valid Factory function. Here’s the simplest way to create Factory functions:
You don’t need
Now that we’ve seen these four OOP setup possibilities, let’s look at how you declare properties and methods on each of them so we can get a little better understanding of working with them before getting to the bigger comparisons we’re trying to make. Declaring properties and methodsMethods are functions declared as an object’s property.
In Object-Oriented Programming, there are two ways to declare properties and methods:
Let’s learn to do both. Declaring properties and methods with ConstructorsIf you want to declare a property directly on an instance, you can write the property inside the constructor function. Make sure to set it as the property for
Methods are commonly declared on the Prototype because Prototype allows instances to use the same method. It’s a smaller “code footprint.” To declare properties on the Prototype, you need to use the
It can be clunky if you want to declare multiple methods in a Prototype.
You can make things easier by using merging functions like
Declaring properties and methods with ClassesYou can declare properties for each instance inside the
It’s easier to declare methods on the prototype. You write the method after
It’s easier to declare multiple methods on Classes compared to Constructors. You don’t need the Note: there’s no
Declaring properties and methods with OLOOYou use the same process for declaring properties and methods on an instance. You assign them as a property of
To declare methods in the prototype, you write the method like a normal object.
Declaring properties and methods with Factory functionsYou can declare properties and methods directly by including them in the returned object.
You cannot declare methods on the Prototype when you use Factory functions. If you really want methods on the prototype, you need to return a Constructor, Class, or OLOO instance. (Don’t do this since it doesn’t make any sense.)
Where to declare properties and methodsShould you declare properties and methods directly on the instance? Or should you use Many people take pride that JavaScript is a “Prototypal Language” (which means it uses prototypes). From this statement, you may make the assumption that using “Prototypes” is better. The real answer is: It doesn’t matter. If you declare properties and methods on instances, each instance will take up slightly more memory. If you declare methods on Prototypes, the memory used by each instance will decrease, but not much. This difference is insignificant with computer processing power what it is today. Instead, you want to look at how easy it is to write code — and whether it is possible to use Prototypes in the first place. For example, if you use Classes or OLOO, you’ll be better off using Prototypes since the code is easier to write. If you use Factory functions, you cannot use Prototypes. You can only create properties and methods directly on the instance. I wrote a separate article on understanding JavaScript Prototypes if you’re interested in finding out more. Preliminary verdictWe can make a few notes from the code we wrote above. These opinions are my own!
We’re down to two. Should we choose Classes or Factory functions then? Let’s compare them! Classes vs. Factory functions — InheritanceTo continue the discussion on Classes and Factory functions, we need to understand three more concepts that are tied closely to Object-Oriented Programming.
Let’s start with Inheritance. What is Inheritance?Inheritance is a loaded word. Many people in the industry use Inheritance incorrectly, in my opinion. The word “inheritance” is used when you receive things from somewhere. For example:
Fairly straightforward. In JavaScript, Inheritance can mean the same thing: where you get properties and methods from the parent blueprint. This means all instances actually inherit from their blueprints. They inherit properties and methods in two ways:
We discussed how to do both methods in the previous article so refer back to it if you need help seeing these processes in code. There’s a second meaning for Inheritance in JavaScript — where you create a derivative blueprint from the parent blueprint. This process is more accurately called Subclassing, but people sometimes will call this Inheritance as well. Understanding SubclassingSubclassing is about creating a derivative blueprint from a common blueprint. You can use any Object-Oriented Programming flavor to create the Subclass. We’ll talk about this with the Class syntax first because it’s easier to understand. Subclassing with ClassWhen you create a Subclass, you use the
For
example, let’s say we want to create a
The
Note:
Let’s say a
Here’s an example of an instance of
Subclassing with Factory functionsThere are four steps to creating Subclasses with Factory functions:
The process looks like this:
We’ll use the same example — creating a
We can create
Then
we add the
Here’s an example of a
Note: You cannot use Overwriting the Parent’s methodSometimes you need to overwrite the Parent’s method inside the Subclass. You can do this by:
The process looks like this with Classes:
The process looks like this with Factory functions:
Inheritance vs. CompositionNo talk about Inheritance ever concludes without the mention of Composition. Experts like Eric Elliot often suggests we should favor Composition over Inheritance.
So let’s give Composition a deeper look and understand what it is. Understanding CompositionComposition is the act of
combining two things into one. It’s about merging things together. The most common (and simplest) way of merging objects is with
The use of Composition can be better explained with an example. Let’s say we already have two Subclasses, a Here’s the code so far:
Now let’s say you want to create a third Subclass. This
Subclass is a mix of a Designer and a Developer — they can design and code. Let’s call it How would you create the third Subclass? We cannot extend The Diamond Problem can be easily solved if we do something like
So we need to rely on Composition. Composition says: Instead of trying to create In practice, it can look like this:
We can then skip Here’s the code for
You can do the same with
Did you notice we’re creating methods directly on the instance? This is just one option. We can still put methods into the Prototype, but I think the code looks clunky. (It’s as if we’re writing Constructor functions all over again.)
Feel free to use whatever code structure you’re attracted to. The results are kinda the same anyway. Composition with Factory FunctionsComposition with Factory functions is essentially adding the shared methods into the returned object.
Inheritance and Composition at the same timeNobody says we can’t use Inheritance and Composition at the same time. We can! Using the example we’ve ironed out so far, Here’s an example where we use both inheritance and composition with the class syntax.
And here’s the same thing with Factory functions:
Subclassing in the real worldOne final point about Subclassing vs. Composition. Even though experts have pointed out that Composition is more flexible (and hence more useful), Subclassing still has its merits. Many things we use today are built with the Subclassing strategy. For example: The Another example: HTML Elements are Subclasses of Nodes. That’s why they can use all properties and methods of Nodes. Preliminary verdictClasses and Factory functions can both use Inheritance and Composition. Composition seems to be cleaner in Factory functions though, but that’s not a big win over Classes. We’ll examine Classes and Factory Functions more in detail next. Classes vs. Factory functions — EncapsulationWe’v looked at the four different Object-Oriented Programming flavors so far. Two of them — Classes and Factory functions — are easier to use compared to the rest. But the questions remain: Which should you use? And why? To continue the discussion on Classes and Factory functions, we need to understand three concepts that are tied closely to Object-Oriented Programming:
We just talked about Inheritance. Now let’s talk about Encapsulation. EncapsulationEncapsulation is a big word, but it has a simple meaning. Encapsulation is the act of enclosing one thing inside another thing so the thing inside doesn’t leak out. Think about storing water inside a bottle. The bottle prevents water from leaking out. In JavaScript, we’re interested in enclosing variables (which can include functions) so these variables don’t leak out into the external scope. This means you need to understand scope to understand encapsulation. We’ll go through an explanation, but you can also use this article to beef up your knowledge regarding scopes. Simple EncapsulationThe simplest form of Encapsulation is a block scope.
When you’re in the block, you can access variables that are declared outside the block.
But when you’re outside the block, you cannot access variables that are declared inside the block.
Note: Variables declared with Encapsulating with functionsFunctions behave like block scopes. When you declare a variable inside a function, they cannot leak out of that function. This works for all variables, even those declared with
Likewise, when you’re inside the function, you can access variables that are declared outside of that function.
Functions can return a value. This returned value can be used later, outside the function.
ClosuresClosures are an advanced form of Encapsulation. They’re simply functions wrapped in functions.
Variables declared in
Encapsulation and Object-Oriented ProgrammingWhen you build objects, you want to make some properties publicly available (so people can use them). But you also want to keep some properties private (so others can’t break your implementation). Let’s work through this with an example to make things clearer. Let’s say we have a
Here we exposed the
Users can also use the
Let’s add a condition and say that each car has a maximum capacity of 100 liters. With this condition, we don’t want to let users set the There are two ways to do prevent users from setting
Private by conventionIn JavaScript, there’s a practice of prepending underscores to a variable name. This denotes the variable is private and should not be used.
We often create methods to get and set this “private”
Users should use the
But
We need to use real private variables if we want to completely prevent users from accessing them. Real Private MembersMembers here refer to variables, functions, and methods. It’s a collective term. Private Members with ClassesClasses let
you create private members by prepending
Unfortunately, you can’t use You need to declare the private variable outside the constructor first.
In this case, we can use a shorthand and declare
You cannot access
You need methods (like
Note: I prefer
Getters and Setters instead of
Private Members with Factory functionsFactory functions create Private Members automatically. You just need to declare a variable like normal. Users will not be able to get that variable anywhere else. This is because variables are function-scoped and hence encapsulated by default.
We can create getter and setter functions to use this private
That’s it! Simple and easy! Verdict for EncapsulationEncapsulation with Factory functions are simpler and easier to understand. They rely on the scopes which are a big part of the JavaScript language. Encapsulation with Classes, on the other hand, requires prepending We’ll look at the final concept — Classes vs. Factory Functions — The this variable
But the concept of The six contexts are:
I covered these six contexts in detail. Give it a read if you need help understanding Note: Don’t shy away from learning to use Come back to this article after you’ve solidified your knowledge on Back yet? Good. Let’s go! Using |