Objects in Javascript


Published on 06 April 2022


Objects in Javascript

Object tutorial in javascript

Object in Javascript can be defined as a property that consists of a series of attributes.
For example, a person can be defined as an object consisting of the attributes name, age, height,...

There are 3 ways to create objects in javascript:

  • We declare an object as a variable name literally, whose interior is formed by its attributes:

  var person = {
    name: 'John',
    age: 25,
    height: 160
 }

  • Object created through a function, then be built through a variable:

function Person(name, age){
    this.name = name;
    this.age = age;
 }
 var person1 = new Person('John', 25);

  • Using new Object as follows:

var person = new Object({
  name: 'John',
  age: 25,
  sayHello: function(){ 
    console.log('Hello');
  }
});

An easy way to run this code is by installing node.js. In the following link we explain how to install node on your computer and its use.

If we save the previous example in a test.js file inside a certain folder, the correct way to execute this inside the console of our PC, either in linux or in Windows from cmd, is through the following nomenclature:

node test.js

The test.js file will have the following content:

  var person = {
    name: 'John',
    age: 25,
    sayHello: function(){ console.log('Hello');}
 };
 console.log(person);

To access any part of the object we do it through the point, that is, to access name, we simply have to write within the code:

console.log(person.name);

To show the sayHello function inside the object, we cannot print it through an external console.log, but directly by writing inside our code:

person.sayHello();

If we want to reference attributes of the object itself within the object, we reference the word "this":

var person = {
  name: 'John',
  age: 25,
  sayHello: function(){ 
    console.log('Hello ' + this.name);
  }
};
person.sayHello();

This example will display the name of the object itself, ie "Hello John".

In the following link of our code editor we will create a player object with an initial force of 10. We have to apply a force to it that increases its force by 1, in addition to being able to query that force with a message:

var player = {
 force: 10,
 increaseForce: function(){
   this.force = this.force + 1;
 },
 messageForce: function(){
   console.log("Force is " + this.force);
 }
}

player.messageForce();

player.increaseForce();

player.messageForce();


Previous Chapter - Next Chapter



Tips on SEO and Online Business

Next Articles

Previous Articles