Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

getters and setters in java script

const student = {

    // data property
    firstName: 'Monica',
    
    // accessor property(getter)
    get getName() {
        return this.firstName;
    },
    //accessor property(setter)
    set setName(newName){
      this.firstName = newName;
  }
};

// accessing data property
console.log(student.firstName); // Monica

// accessing getter methods
console.log(student.getName); // Monica

// trying to access as a method
console.log(student.getName()); // error

// change(set) object property using a setter
student.changeName = 'Sarah';

console.log(student.firstName); // Sarah

Source by www.programiz.com #
 
PREVIOUS NEXT
Tagged: #getters #setters #java #script
ADD COMMENT
Topic
Name
1+1 =