
Objects in JavaScript and creating a JS component. Part 1
- Transfer
- Tutorial
This article is the first part of a tutorial about OOP in JavaScript and how to create a simpleJS component .
About objects and JavaScript
Think of an object as a set of
JavaScript is an
JavaScript is based on a simpleobject-oriented paradigm. An object is a collection of properties, and a property is an association between a name and a value. The value of the property may 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 object properties through dot notation . But before dealing with access to properties, let's figure out how to create and initialize objects.
Object Creation
Surely you already created or used objects without knowing it, since everything in JavaScript is an object. A short note with MDN:
All primitive types, exceptnull
and areundefined
considered as objects. They can be assignedsome properties, and they have all the characteristics of objects.
JavaScript has a huge number of standard objects, but in this article I will not consider them. From now on and throughout this article, we will create a very simple
var simpleAlert = new Object();
// От переводчика: на самом деле, объект можно создать ещё проще.
var simpleAlert = {};
That's all! Simple, right? However, all this does not make sense until we add
// создание нового объекта
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’s console, we could do the following:
// вывод сообщения об ошибке
alert(simpleAlert.sa_error);
This is just one way to create an object and access its properties.
Creating an object with initializers
Another way to create an object is by using the so-called object initializer , object initializers . Definition on MDN:
... you can create objects using the object initializer. Using an initializer is sometimes called creating an object using literal notation . The name object initializer also follows the terminology used inC ++ .
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 instance:
// создание нового объекта
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 print 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 .
Using constructor
Another way to create an object in JavaScript is to use a
Define an object by writing a constructor. Capitalizing a function is considered good practice. Create an instance of the object 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, then we will 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 is that it can be used to create multiple instances of an object with a different set of properties. Properties can also be objects and functions.
More details about objects
In fact, you can tell a lot more about objects than I said 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. It is also worth looking at the documentation for objects 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”, which displays a message on the user's screen when he clicks on the button. The button that will be displayed depends on which button is pressed. Button layout:
As for the component itself, we wrap its code in an anonymous function and make it available in the global scope. To start, it will look something
;(function( window ) {
'use strict';
})( window );
A few notes about the code:
- I use
strict mode
. You can read about it here . - We pass
window
in our anonymous function, so we can later add SimpleAlert to the global scope.
Let's write some code for our component. First we need to create a function
SimpleAlert
. 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 the SimpleAlert object, nothing will happen so far.
(function() {
/**
* Отобразить стандартное уведомление
*/
var default_btn = document.getElementById( "default" );
default_btn.addEventListener( "click", function() {
var default_alert = new SimpleAlert("Hello World!");
} );
})();
Before continuing, you should familiarize yourself with
Object.prototype
. MDN:All objects in JavaScript are descendantsObject
; all objects inherit properties and methods fromObject.prototype
, although they can be overridden. An exception is an object with anull
prototype, for exampleObject.create(null)
).
More details . We will use this approach in creating our component. Let's add a function
init
, and call it immediately after creating the object. 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 instantiated object will display the message “Hello, world!” In the console . This is progress! Now let's make the message appear on the user's screen, and not on 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 in our code.
- We create a variable
message
inside the constructor and make it available inside the anonymous function withthis.message = message
. - Next, we call our function
_init
throughthis._init()
. Each time we create a new instance of the object, these two steps are automatically performed. - Inside
_init()
we declare the necessary variables using the keywordthis
. Then we get access to the element#component
, and put in itdiv
containing the message.
Very neat, right?
Whole code
Below is all the written code, including some CSS for a nicer look. To start the markup:
Same as above. Now some CSS :
.simple-alert {
padding: 20px;
border: solid 1px #ebebeb;
}
Edit it the way you want! And finally, the
// 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
hide()
). In the next part, we will improve SimpleAlert a bit, and also learn how to set default parameters and how to pass custom 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!