[Javascript] Accessor function

Suyeon·2020년 9월 17일
0

Javascript

목록 보기
18/31

In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords:

  • get - to define a getter method to get the property value
  • set - to define a setter method to set the property value

Advantages

  • It is useful to modify or perform date before saving (such as validation).
  • It make it inaccessible from other code (encapsulation).

If you want a value that's based on some other values: someone's full name, for example, is a concatenation of their first and last names.

// Ugly
person.setLastName('Smith');
person.setFirstName('Jimmy');
person.getFullName(); // Jimmy Smith
  • Access fullName as a function: person.fullName().
  • You made unnecessary extra function.

Getter and setter

Getter ans setter save you!

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}
person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin
  • Access fullName as a property: person.fullName.

Object.defineProperty

you can also use Object.defineProperty() method to add getters and setters.

  • Object.defineProperty(obj, prop, descriptor)
  • The first argument is the objectName.
  • The second argument is the name of the property.
  • The third argument is an object that describes the property.
let student = {
    firstName: 'Monica'
}

// getting property
Object.defineProperty(student, "getName", {
    get : function () {
        return this.firstName;
    }
});

// setting property
Object.defineProperty(student, "changeName", {
    set : function (value) {
        this.firstName = value;
    }
});

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

// changing the property value
student.changeName = 'Sarah';

console.log(student.firstName); // Sarah
profile
Hello World.

0개의 댓글