The private access modifier

If we use the private modifier, the method or property can only be accessed by the object that owns them.

The following example redeclares, once more, the classes that we declared in the preceding example, but uses the private access modifier instead of the public modifier. The example also adds a couple of extra methods to the classes to demonstrate the implications of using a private access modifier:

class Person { 
    public name: string; 
    public surname: string; 
    private _email: string; 
    public constructor( 
        name: string, surname: string, email: string 
    ) { 
        this._email = email; 
        this.name = name; 
        this.surname = surname; 
    } 
    public greet() { 
        console.log("Hi!"); 
    } 
    public getEmail() { 
        return this._email; 
    } 
} 
 
class Teacher extends Person { 
    public teach() { 
        console.log("Welcome to class!"); 
    } 
public shareEmail() { 
        console.log(`My email is ${this._email}`); // Error 
    } 
} 

If we create an instance of both the Person and Teacher classes, we will be able to observe that the getEmail method, which belongs to the Person instance, can access the private property. However, the private property, email, cannot be accessed from the method named shareEmail, which is declared by the derived  Teacher class. Also, other objects (such as the console object) cannot access the private property. This code snippet confirms that the email property can only be accessed by the instances of the Person class:

const person = new Person( 
    "Remo", 
    "Jansen", 
    "remo.jansen@wolksoftware.com" 
); 
 
const teacher = new Teacher( 
    "Remo", 
    "Jansen", 
    "remo.jansen@wolksoftware.com" 
); 
 
console.log(person._email); // Error 
console.log(teacher._email); // Error 
teacher.getEmail();

We can update the Teacher class to use the public getEmail method instead of trying to access the private property directly:

class Teacher extends Person { 
    public teach() { 
        console.log("Welcome to class!"); 
    } 
    public shareEmail() { 
        console.log(`My email is ${this.getEmail()}`); // OK 
    } 
}