【问题标题】:Why are private members accessible through the square bracket notation?为什么私有成员可以通过方括号表示法访问?
【发布时间】:2021-05-13 11:56:20
【问题描述】:

考虑以下小sn-p:

class BlueprintNode {
    private metadata: number[] = [];
}

var node = new BlueprintNode();
node["metadata"].push("Access violation, rangers lead the way.");

Demo on TypeScript Playground

TypeScript 编译器如何允许通过使用方括号表示法访问私有成员?它甚至可以正确检测给定属性的类型。使用点符号,它会正确显示编译错误。

【问题讨论】:

  • 我猜这是因为方括号表示法适用于任何对象,并且 TypeScript 希望尽可能接近 JavaScript。我认为尝试限制您使用方括号是没有意义的,即使编译器能够检查 node["metadata"] 实际上是私有属性,因为您始终可以通过使用像 node[propName] 这样的变量来绕过此检查.顺便看看这个答案:stackoverflow.com/a/12713869/310726

标签: typescript


【解决方案1】:

当使用索引访问对象属性时,编译器会这样对待对象:

interface BlueprintNode {
    metadata: number[];
    [key: string]: any;
}

如果你这样做:

let node: BlueprintNode;
node["metadata"].push("Access violation, rangers lead the way.");

您会遇到与您的代码相同的错误。

【讨论】:

    【解决方案2】:

    为什么 TypeScript 允许使用方括号访问私有方法:

    const privateMethodClass: PrivateMethodClass = new PrivateMethodClass();
    
    let result: boolean;
    
    result = privateMethodClass.getFlag();  //result = false
    
    // Accessing private method using square brackets
    
    privateMethodClass[ "setFlag" ]( true );
    
    result = privateMethodClass.getFlag();  //Result = true
    
    class PrivateMethodClass {
    
        private flag: boolean = false;
    
        private setFlag( flag: boolean ): void {
            this.flag = flag;
        }
    
        public getFlag(): boolean {
            return this.flag;
        }
    }
    

    【讨论】:

    • 如果您有其他问题,可以点击提问。
    猜你喜欢
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多