S
S
Sergey2021-06-21 13:21:58
JavaScript
Sergey, 2021-06-21 13:21:58

How to create an object in JS?

Good afternoon.

Tell me how to create an object in jS?

If specified as:

let user = {
  name: "John",
  age: 30,
};


That is mutable data.

And I also want to add data that cannot be changed, like this:

const user = {
proff: "ingeneer"
};

And tell me how to unite (and is it possible to do so) to specify what will be immutable and what is mutable for this object?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kovalsky, 2021-06-21
@oldzas

Probably somehow using private variables:

class User {
    #proff;

    constructor(name, age, proff) {
        this.name = name;
        this.age = age;
        this.#proff = proff;
    }

    get proff() {
        return this.#proff;
    }
}

const my_user = new User('name', 29, 'luftwaffe');

console.log(my_user.age); // 29
my_user.age = 92;
console.log(my_user.age); // 92

console.log(my_user.proff); // luftwaffe
my_user.proff= 'kriegsmarine';
console.log(my_user.proff); // luftwaffe

You can also use defineProperty and writable: false, but this is somehow not very beautiful

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question