typescript 缺乏对类属性的访问权限

x33g5p2x  于 2023-01-03  发布在  TypeScript
关注(0)|答案(1)|浏览(206)

我有一个秒表方法,它有几个属性,我不希望任何人能够从类外访问它们,我把它们设为私有的,但是仍然可以访问它们,并且它们的值可以更改,我该怎么做?

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();
mepcadol

mepcadol1#

正如Hrusikesh在问题注解中指出的,TypeScript可见性修饰符只在编译时执行,在运行时,类成员总是像任何JavaScript对象属性一样可访问:
与TypeScript类型系统的其他方面一样,privateprotected仅在类型检查期间实施。
但是现在有了JavaScript类private features:只要在成员名前面加上一个hash(#),它就真的是"私有的",也就是说,即使在编译之后,也不能从类的外部访问,因为它是由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链接

相关问题