The number of ways one can create Objects in JavaScript can be quite overwhelming. JavaScript is a unique language where almost EVERYTHING is an Object. It is not an exaggeration when I say, even Functions in JavaScript are Objects. This article is a detailed re-introduction to Objects, to refresh one's basics if already familiar, or introduce the newbies to Object Oriented Programming in JS.
Having said that, let's dive in:
What is an object?
Simply put, it's a group of anything! Usually, a group of some related data and functionalities put together make an object. There is nothing more or less to it. So I will not get into the bookish definitions.
For example, details about a person can be represented as an object:
Name
Age
Country
In JS we have a particular way of representing this object- Curly Braces with key-value pairs! It's nothing but JavaScript's Object Notation or JSON. (Oh! I have heard this!)
var person0 = {
name: 'Juan',
age: 25,
country: 'Mexico'
};
And there you have your first object. 😊
But remember I told you, some data and functions. So let's add a function:
var person0 = {
name: 'Juan',
age: 25,
country: 'Mexico',
greeting: function() {
console.log('Hola! Mi nombre es Juan');
}
};
Eazy-Peezy!
Wondering why are you able to add a function inside an object? Well, remember even Functions in JS is an Object! So this is simply a nested object. An object inside an object.
What happens when you call person0.greeting()
? You guessed it right, "Hola! Mi nombre es Juan"
This way of declaring an object in JS is called Object Literal.
But, what happens if you change person0's name?
i.e. person0.name = 'Maria';
Then, calling person0.greeting()
still prints "Hola! Mi nombre es Juan"
.
Let's fix this. Instead of hard-coding "Juan", we simply fetch the current 'name' in the object-
var person0 = {
name: 'Juan',
age: 25,
country: 'Mexico',
greeting: function() {
console.log('Hola! Mi nombre es ' + this.name);
}
};
this
holds the current scope where the function is called, which in our case in person0. Now, if you change person0's name in future, the greeting()
function will update its output accordingly.
Unfortunately, the concept of scope is 'out of scope' of this article. Pun Intended! 😂 I promise to cover it later.
You have done well 🤗. Take a break. Digest this. Then move on to #2.
Reference:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
Top comments (0)