📜 ⬆️ ⬇️

Objects in javascript and create js component. Part 1

This article is the first part of the tutorial on OOP in JavaScript and on creating a simple JS component .

About objects and javascript


Think of an object as a collection of things. For example, imagine that you have a bicycle. This bike is an object , and it has a combination of some features / parts / etc called object properties . An example of such a property is the model of a bicycle, the year of its production, its details. Details may also have their own set of properties.

JavaScript is an object-oriented language. Therefore, everything in JavaScript is an object and has its own set of properties that we can access. More formal explanation with MDN:
JavaScript is based on a simple object-oriented paradigm. An object is a collection of properties, and a property is an association between a name and a value. The value of a property can be a function, in which case the function will be called a method. In addition to the standard objects already defined in the browser, you can create your own objects.

Creating your own objects is a very useful feature. In JavaScript, we can access the properties of the object through dot notation . But before we deal with access to properties, let's deal with the creation and initialization of objects.

Object creation


Surely you have already created or used objects without knowing it, since everything in JavaScript is an object. Short note with MDN:
All primitive types except null and undefined treated as objects. They can be assigned some properties, and they have all the characteristics of objects.

In JavaScript, there are a huge number of standard objects, but in this article I will not consider them. From now on and throughout the article, we will create a very simple JavaScript component called “SimpleAlert”. Because of this, let's create our own object.
')
 var simpleAlert = new Object(); //  :   ,     . var simpleAlert = {}; 

That's all! Simple, isn't it? However, all this does not make sense until we add any properties to the object. We can do this using dot notation :

 //    var simpleAlert = new Object(); //    simpleAlert.sa_default = "Hello World!"; simpleAlert.sa_error = "Error..."; simpleAlert.sa_success = "Success!"; //     console.log(simpleAlert); 

The console shows that our object has 3 properties. Since we set these properties above, we can access them anywhere in our script. For example, if we wanted to send an error notification to the user console, we could do the following:

 //     alert(simpleAlert.sa_error); 

This is just one of the ways to create an object and access its properties.

Creating an object with initializers


Another way to create an object is with the help of the so-called object initializer , object initializers . Definition on MDN:
... you can create objects using an object initializer. Using an initializer is sometimes called creating an object with literal notation . The object initializer name also corresponds to the terminology used in C ++ .

Creating our “SimpleAlert” in this way will be quite simple:

 //    var simpleAlert = { sa_default : "Hello World!", sa_error : "Error...", sa_success : "Success!" } //     console.log(simpleAlert); 

Object properties can also be functions. For example:

 //    var simpleAlert = { sa_default : "Hello World!", sa_error : "Error...", sa_success : "Success!", sa_fallback : function(){ console.log("Fallback"); } } //  fallback'a simpleAlert.sa_fallback(); 

The code above will output the string “Fallback” to the console. As mentioned above, when a property of an object is a function, it can also be called a method .

Constructor use


Another way to create an object in JavaScript is to use a constructor function . And again quote from MDN:
Define an object by writing a constructor. A good practice is to name a function with a capital letter. Create an object instance using the `new` keyword.

You can read more about this method here . Creating our object using the constructor:

 //  function SimpleAlert( sa_default, sa_error, sa_success ) { this.sa_default = sa_default; this.sa_error = sa_error; this.sa_success = sa_success; } //    var my_alert = new SimpleAlert( "Hello World!", "Error...", "Success!" ); 

If we display the object in the console, we get the same result as in the previous cases.

 console.log(my_alert); //   console.log(my_alert.sa_error); //  "Error..." 

The elegance of this method lies in the fact that with its help you can create several instances of an object with a different set of properties. Properties can also be objects and functions.

More details about the objects


In fact, much more can be said about objects than I described above. However, the methods mentioned by me are very useful, and in the future we will use them to create our component. I strongly recommend reading the material with MDN Working with objects in order to fully understand the objects. You should also take a look at the documentation on the objects in order to have an idea of ​​what methods and properties to work with them exist.

Create parts of our component


We are going to create a component called “SimpleAlert” that displays a message on the screen of the user when he presses a button. The button that will be displayed depends on which button is pressed. Markup for buttons:

 <div id="component"> <button id="default">Show Default Message</button> <button id="success">Show Success Message</button> <button id="error">Show Error Message</button> </div> 

As for the component itself, we will wrap its code in an anonymous function and make it available in the global scope. To begin with, it will look something like this:

 ;(function( window ) { 'use strict'; })( window ); 

A few comments about the code:



Let's write some code for our component. First we need to create the SimpleAlert function. We also need it in the global scope.

 ;(function( window ) { 'use strict'; /** * SimpleAlert function */ function SimpleAlert( message ) { this.message = message; } //    ... /** *  SimpleAlert     */ window.SimpleAlert = SimpleAlert; })( window ); 

If we create an instance of a SimpleAlert object, so far nothing will happen.

 (function() { /** *    */ var default_btn = document.getElementById( "default" ); default_btn.addEventListener( "click", function() { var default_alert = new SimpleAlert("Hello World!"); } ); })(); 

Before proceeding, you should familiarize yourself with the Object.prototype . MDN:
All objects in JavaScript are descendants of Object ; all objects inherit properties and methods from Object.prototype , although they can be overridden. The exception is an object with a null prototype, for example Object.create(null) ).

More details . We will use this approach in creating our component. Let's add the init function, and call it right after the object is created. This function will send a message to the console.

 ;(function( window ) { 'use strict'; /** * SimpleAlert function */ function SimpleAlert( message ) { this.message = message; this._init(); } /** * Initialise the message */ SimpleAlert.prototype._init = function() { console.log(this.message); } /** * Add SimpleAlert to global namespace */ window.SimpleAlert = SimpleAlert; })( window ); 

Now the created object instance will display the message “Hello, world!” To the console. This is progress! Now let's make it so that the message is displayed on the screen of the user, and not to the console.

 ;(function( window ) { 'use strict'; /** * SimpleAlert function */ function SimpleAlert( message ) { this.message = message; this._init(); } /** * Initialise the message */ SimpleAlert.prototype._init = function() { this.component = document.getElementById("component"); this.box = document.createElement("div"); this.box.className = "simple-alert"; this.box.innerHTML = this.message; this.component.appendChild( this.box ); } /** * Add SimpleAlert to global namespace */ window.SimpleAlert = SimpleAlert; })( window ); 

Let's take a look at the points of our code.

  1. We create the message variable inside the constructor and make it available inside the anonymous function using this.message = message .
  2. Next, we call our _init function via this._init() . Each time we create a new instance of an object, these two steps are automatically executed.
  3. Inside _init() we declare the variables we need using the this . Then we get access to the element #component , and in it we place the div containing the message.


Very neat, right?

All code


Below is all the written code, including some CSS for a more pleasing look. First, the markup:

 <div id="component"> <button id="default">Show Default Message</button> <button id="success">Show Success Message</button> <button id="error">Show Error Message</button> </div> 

The same which was higher. Now for some CSS :

 .simple-alert { padding: 20px; border: solid 1px #ebebeb; } 

Edit it as you like! And finally, the JS code . I also added event handlers to it so that when a button is clicked, the message is displayed correctly.
 // COMPONENT // // The building blocks for our SimpleAlert component. //////////////////////////////////////////////////////////// ;(function( window ) { 'use strict'; /** * SimpleAlert function */ function SimpleAlert( message ) { this.message = message; this._init(); } /** *   */ SimpleAlert.prototype._init = function() { this.component = document.getElementById("component"); this.box = document.createElement("div"); this.box.className = "simple-alert"; this.box.innerHTML = this.message; this.component.appendChild( this.box ); this._initUIActions; } SimpleAlert.prototype._initUIActions = function() { } /** *  SimpleAlert     */ window.SimpleAlert = SimpleAlert; })( window ); // EVENTS // //       //     . //////////////////////////////////////////////////////////// ;(function() { /** * Show default */ var default_btn = document.getElementById( "default" ); default_btn.addEventListener( "click", function() { var default_alert = new SimpleAlert("Hello World!"); } ); /** * Show success */ var default_btn = document.getElementById( "success" ); default_btn.addEventListener( "click", function() { var default_alert = new SimpleAlert("Success!!"); } ); /** * Show error */ var default_btn = document.getElementById( "error" ); default_btn.addEventListener( "click", function() { var default_alert = new SimpleAlert("Error..."); } ); })(); 


Summarize


In this article, we looked at creating a simple JavaScript component using objects. This component is simple, but its code gives us the fundamental knowledge to create reusable and extensible components. At leisure, think about how you can implement the “close alert” button (hint - pressing the button should launch the hide() method).

In the next section, we will slightly improve SimpleAlert, as well as learn how to set default parameters and how to pass our own parameter sets. That's when all the beauty of programming will be visible in action!

I hope you enjoyed this article. Wait for the second part. Thank you for reading!

Source: https://habr.com/ru/post/240375/


All Articles