美文网首页
使用哈希前缀#将类字段设为私有

使用哈希前缀#将类字段设为私有

作者: 泪滴在琴上 | 来源:发表于2022-04-27 11:28 被阅读0次

    在类中通过哈希前缀#标记的字段都将被私有,子类实例将无法继承

    例如

    class ClassWithPrivateField {
        #privateField;
        #privateMethod() {
            return 'hello world';
        }
        constructor() {
            this.#privateField = 42;
        }
    }
    
    const instance = new ClassWithPrivateField()
    console.log(instance.privateField); //undefined
    console.log(instance.privateMethod); //undefined
    

    可以看到,属性privateField和方法privateMethod都被私有化了,在实例中无法获取到

    相关文章

      网友评论

          本文标题:使用哈希前缀#将类字段设为私有

          本文链接:https://www.haomeiwen.com/subject/efbisrtx.html