JavaScript Object

In JavaScript we can create an object in various ways. In fact, to create an object in JavaScript we can also use other methods than what we saw in the previous lessons and in particular we can use the constructor object.

Examples of using JavaScript object

Let’s create an example where, to create an object, we use the new keyword together with the object () constructor.

let person = new Object();
person.name = "Coding";
person.lastname = "Creativo";
person.age = 30;

After creating the object instance we can define the various properties always using the dot notation, to which we will assign values.

Later we can view them simply by calling each property like this:

console.log(person.name);
console.log(person.lastname);
console.log(person.age);

You can also define methods, as we have seen in previous lessons, by assigning a function to an object property.

In our case we assign a function to the greet property that has the task of displaying an alert when called.

let person = new Object();
person.name ="Coding";
person.lastname = "Creativo";
person.age = 30;

persona.greet = function (){
  alert('Hello ' + person.name);
}

persona.greet();

Then by calling the greeting () method on our person object, the alert will appear with the appropriate greeting. Of course, the greeting method can also be called on another instance.

JavaScript Object – constructing an object from primitive data

In JavaScript it is possible to construct an object starting from a primitive data type, such as a number or a string.

let number = new Object(5.67895);
let str = new Object('Coding Creativo');

What you get then is a string or number object.

In fact, if we try to make the console log, we will see objects in our console.

console.log(number);
console.log(str);

Here is the result obtained in our console:

object in javascript

You can also see that it is an object simply by typing on number or on string:

console.log(typeof(number));

So we can for example use the toFixed () method on the object number.

So let’s add this line of code:

number = number.toFixed(2);

And then we do the console.log:

console.log(number);

Conclusion

In this lesson we have seen how to use in JavaScript the object constructor, in the next lesson we will deal with object oriented programming again.

Alcuni link utili

Indice argomenti tutorial JavaScript

12 commenti a “JavaScript Object”

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *