“JavaScript Getters et Setters” Réponses codées

JavaScript Getters et Setters

class Person {
    constructor(name) {
        this.name = name;
    }
    // getter
    get personName() {
        return this.name;
    }
    // setter
    set personName(x) {
        this.name = x;
    }
}
let person1 = new Person('Jack');
console.log(person1.name); // Jack

// changing the value of name property
person1.personName = 'Sarah';
console.log(person1.name); // Sarah
SAMER SAEID

Getters et 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

Worried Wolverine

Getters et Setters

For IntelliJ IDEA TO generate getters and setters:
Refactor-->EncapsulatFields 
OR
use Keyboard Shortcut: alt + insert
AL momani

Réponses similaires à “JavaScript Getters et Setters”

Questions similaires à “JavaScript Getters et Setters”

Plus de réponses similaires à “JavaScript Getters et Setters” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code