Javascript Class Create private attributes via Symbol

Description

Javascript Class Create private attributes via Symbol

//using symbols for private atributes

var _name = Symbol();
class Person2 {//from   ww  w  . j  a va 2s.  c  om

    constructor (name) {
        this[_name] = name;
    }

    get name() {
        return this[_name];
    }

    set name(value) {
        this[_name] = value;
    }
}

let lotrChar2 = new Person2('Frodo');
console.log(lotrChar2.name);
lotrChar2.name = 'Gandalf';
console.log(lotrChar2.name);

console.log(Object.getOwnPropertySymbols(lotrChar2));



PreviousNext

Related