Javascript OOP with DOM
There are ways Object Oriented Programmings are done, but Javascript has its unique way of getting things done in a simple and flexible way.
We’ll be creating a login page in this tutorial using OOP with DOM and by the end of this tutorial, you’ll know how to write a nice OOP in Javascript by interacting with DOM.
This tutorial won’t start from Object literal and won’t include use of Class keyword, but please comment at the bottom in case you need to know how Javascript Objects work from scratch and how to use Class keyword.
Javascript OOP pattern
There are several OOP patterns in Javascript but in this tutorial, we’ll be considering Constructor pattern only. Constructors are functions that initializes object instances, such that they can contain the properties and hold methods that make use of those properties.
Step 1: Create a constructor function
Know that every function expression is a constructor.
From the snippet above, login function is the constructor (function expression) holding the properties and will later hold the methods as well. A method, simply put, is a function that make use of created properties to perform an activity.
“this” keyword is used to declare properties of a constructor and you pass string or number directly if you’re not dealing with DOM. But in this case we’ll continue to create our prototype methods.
Step 2: Create a prototype method
The prototype method is available in all function expression to create method chains in a simpler way. The snippets below illustrate two simple ways to create a prototype method. The first one is shown below:
the login.prototype is assigned to an object literal, in which the logUser() method is embedded. the logUser() method confirms if the user entered something or not by listening to the clicking of the submit button on line 3. Notice how the user email value is collected and compared, the reason why we can access the value property of our DOM element is because the object properties operates like “scoped” variable.
The localStorage() function is used to store user input in the browser if the user entered the email and password.
“user” object was created by instantiating the login constructor on line 19 while the logUser() method is finally invoked on line 20.
The second way we can use the prototype method of a function is shown below:
the major difference is that instead of assigning login.prototype to an object literal like we did earlier, it’ll have its method assigned to a function like seen on line 1 above. Then, it could be invoked as done in the first example.
Step 3: Create your HTML and CSS
Your HTML and CSS can come first or last but you may like to write your HTML as I did below:
the final output will be like this:
I believe this article is clear enough to launch anyone into writing OOP in Javascript, please ask your questions in the comment section.
Thanks!