less than 1 minute read

자바스크립트의 은닉화

class Something {
    #property;

    constructor() {
        this.#property = "test";
    }

    #privateMethod() {
        return 'hello world';
    }

    getPrivateMessage() {
        return this.#property;
    }
}

const instance = new Something();
console.log(instance.property); //=> undefined
console.log(instance.privateMethod); //=> undefined
console.log(instance.getPrivateMessage()); //=> test
console.log(instance.#property); //=> Syntax error

샵 프리픽스를 이용한 은닉화

const counter = (() => {
    let count = 0;

    return () => {
        return count += 1;
    };
})();

console.log(counter()); // 1
console.log(count); // error count is not defined

클로저를 이용한 은닉화

class Counter {
    private count: number
    constructor() {
        this.count = 0
    }

    counting(): void {
        console.log(++this.count)
    }
}

const counter = new Counter()
counter.counting() // 1
counter.counting() // 2
counter.count = 99; // error: Property 'count' is private and only accessible within class 'Counter'.

타입스크립트를 이용한 은닉화

Updated: