JavaScript Object methods and this keyword

JavaScript Object methods and this keyword

Hello everyone, in this article we are going to talk about this keyword and Object methods in Javascript. We will make some examples for better understanding.

Let's get started.

We can create objects with its own functions and properties. Below you can see an example of an object.

const person = {
    name: 'Burak Hamdi',
    surname: 'TUFAN',
    web: 'thecodeprogram.com',
    sayHello: function() { console.log('Hello World!'); }
};

In this object we created an object with name, surname and web informations. We also implemented a function to this object.

In object we need to specify the function with the function() keyword. We can access them with same way as we remember dot notation from other programming languages.
Below you can see the example of function calling.

person.sayHello();
This keyword of JavaScript objects.

this keyword in javascript allows us to access internal properties within object functions. We can use the objects' properties with this keyword

Below you can see the example

const person = {
    name: 'Burak Hamdi',
    surname: 'TUFAN',
    web: 'thecodeprogram.com',
    introduce: function() { console.log('Name : ' + this.name + ", Surname :" + this.surname + ", Web: " + this.web); }
};
person.introduce();
Javascript this keyword example output

We can also manipulate internal datas with functions and this keyword.


const student = {
     name : "Burak Hamdi",
     setName : function(_name) { this.name = _name ;  }
};
console.log(student);
student.setName("TheCodeprogram");
console.log(student);
Below you can see example output: This Keyword in JavaScript object Example Output with Setter method

As you can see above example we can access the internal datas of objects with this keyword. We can also use getter methods with this keyword. All we need to implement the getter function as we do it in other OOP programming languages.


const student = {
     name : "Burak Hamdi",
     getName : function() { return this.name;  }
};
console.log(student.getName());

That is all in this article. In JavaScript object management is easy and using methods within objects make them more useful and readable.

Burak Hamdi TUFAN.


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...