Thursday, August 26, 2021

Object Methods in Javascript Basic Guideline

In this post we will learn Object method to access properties.

// Created Object in Javascript..

const anil = {
firstName: 'Anil',
lastName: 'Singh',
age: 1990,
job: 'programmer',
haveDriverLicence: true,
friends: ['ram', 'shyam', 'sohan'],
calcAge: function (birthYear) {
return 2021 - birthYear;
},
}

// dot notation display properties..
console.log(anil.calcAge(1990));

// bracket notation
console.log(anil['calcAge'](1990));


// Using this keyword to access property in object method

const anil = {
firstName: 'Anil',
lastName: 'Singh',
birthYear: 1990,
job: 'programmer',
haveDriverLicence: true,
friends: ['ram', 'shyam', 'sohan'],
calcAge: function () {
// console.log(this);
return 2021 - this.birthYear;
},
}
console.log(anil.calcAge());

// calculate the age and store in object and use it for simple

const anil = {
firstName: 'Anil',
lastName: 'Singh',
birthYear: 1990,
job: 'programmer',
haveDriverLicence: true,
friends: ['ram', 'shyam', 'sohan'],
calcAge: function() {
this.age = 2021 - this.birthYear;
return this.age;
} }
console.log(anil.calcAge());
console.log(anil.age);
console.log(anil.age);


// Problem - Anil is 31 years old programmer and has driver licence if not have driver licence.

const anil = {
firstName: 'Anil',
lastName: 'Singh',
birthYear: 1990,
job: 'programmer',
haveDriverLicence: true,
friends: ['ram', 'shyam', 'sohan'],
calcAge: function () {
this.age = 2021 - this.birthYear;
return this.age;
},
getSummery: function () {
return `${this.firstName} is ${this.calcAge()} years old ${
this.job
} and he has ${this.haveDriverLicence ? 'a' : 'No'} Driver Licence.`
},
}
console.log(anil.getSummery());

0 comments

Post a Comment