Search code examples
typescriptprivate

Accessing private properties from outside


I faced a 'strange' behaviour in typescript:

    class A {
        private _prop;

        public a() {
            let x = new A();
            x._prop
        }
    }

does not raise any exception, whereas I am accessing a private property from outside an object.

Does someone know:

  • if it's a normal behaviour (I guess yes)
  • where I can find some literature about this? I found it very confusing...

edit I meant: the compiler does not show any exception, where as I access private property _prop from outside object x. I am not speaking about run time.


Solution

  • This is normal behavior, you are in the same class context, which means you can access the private property even it is new instance.

    Here is the C# equivalent of same behavior (valid)

    public class A
    {
        private int _prop;
        public void MyMethod()
        {
            var x = new A();
            x._prop = 5;
        }
    }