Wednesday, July 25, 2018

getter & setter in Javascript

const person={
    firstName: "Jitendra",
    lastName: "Singh",
    get fullName(){
        return `${person.firstName} ${person.lastName}`;
    },
    set fullName(value){
        const parts=value.split(' ');
        this.firstName=parts[0];
        this.lastName=parts[1];
    }
}

console.log(person.fullName);//Jitendra Singh
person.fullName="Jon Smith";
console.log(person.fullName);//Jon Smith
// console.log(person);/{ firstName: 'Jon',
                        // lastName: 'Smith',
                        // fullName: [Getter/Setter] }

No comments:

Post a Comment

Find the value from array when age is more than 30

 const data = [   { id: 1, name: 'Alice', age: 25 },   { id: 2, name: 'Bob', age: 30 },   { id: 3, name: 'Charlie', ...