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.
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.
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
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();
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:
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.
Comments