A
A
AlphaDMQ2018-01-31 22:33:39
JavaScript
AlphaDMQ, 2018-01-31 22:33:39

How to prevent explicit change of the fullName property?

function User(fullName) {
    if (!~fullName.indexOf(' ')) throw new TypeError('Must be 2 words');

    this.fullName = fullName;

    Object.defineProperties(this, {
        firstName: {
            get: function () {
                return this.fullName.split(' ')[0];
            },

            set: function (newFirstName) {
                this.fullName = newFirstName + ' ' + this.lastName;
            },

            configurable: false,
            enumerable: true
        },
        lastName: {
            get: function () {
                return this.fullName.split(' ')[1];
            },

            set: function (newLastName) {
                this.fullName = this.firstName + ' ' + newLastName;
            },

            configurable: false,
            enumerable: true
        }
    });
}

let person = new User("Василий Палкин");

// person.fullName = 'It must not work!'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2018-01-31
@AlphaDMQ

It would be more logical to do the opposite - set firstName and lastName separately, and make fullName a calculated field.
And use es6 classes.

class User {
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question