Home > Software design >  Lack of access to class properties
Lack of access to class properties

Time:01-01

I have a stopwatch method that has several properties, I want no one to be able to access them from outside the class, I made them private, but it is still possible to access them and their value can be changed. what do I do?

class StopWatch {
    private duration: number = 0;
    private status: string = 'stopped';
    private currentTime: number = 0;
    start () {
        if (this.status == 'started') {
            throw new Error("already started!");
        }
        this.currentTime = Date.now();
        this.status = "started";
    }
    stop() {
        if (this.status == "stopped") {
            throw new Error("already stopped!");
        }
        this.duration = Date.now() - this.currentTime   this.duration;
        this.status = "stopped";
        console.log((this.duration / 1000).toFixed(1));
    }
    reset() {
        if (this.status == 'started') {
            this.stop();
        }
        this.duration = 0;
    }
}
const obj = new StopWatch();

CodePudding user response:

As pointed out by Hrusikesh in the question comments, TypeScript visibility modifiers are enforced only at compile time. At runtime, your class members are always accessible like any JavaScript object properties:

Like other aspects of TypeScript’s type system, private and protected are only enforced during type checking.

But there are now JavaScript class private features: just prefix the member name with a hash (#), and it will be truly "private", i.e. not accessible from outside the class, even after compilation, since it is enforced by JavaScript:

class StopWatch2 {
    #duration: number = 0;

    method() {
        console.log("method", this.#duration);
    }
}

const obj2 = new StopWatch2();
obj2.method();
// [LOG]: "method",  0 

console.log("obj2", obj2.#duration); // Error: Property '#duration' is not accessible outside class 'StopWatch2' because it has a private identifier.
// Does not even run!

Playground Link

  • Related