TypeScript public/protected/private example

TypeScript lets you do inheritance in Javascript, but the restrictions are enforced at compile time, rather than the typical Javascript tendency to randomly throw errors whenever the browser feels like it.

Part of this is enforcement of access specification:

class Dialog {
    message: String;
 
    render() {
    }
 
    public e() {
        console.log("e");   
    }
 
    protected f() {
        console.log("f");
    }
 
    private g() {
        console.log("g");
    }
}
 
class AlertDialog extends Dialog {
     render() {
         this.e();
         this.f();
     }    
 
     public e() {
          super.e();
         console.log("e - child"); 
     }     
     protected f() {
         console.log("f - child");
     }
}
 
let ad: Dialog = new AlertDialog();
ad.render();

This prints out the following:

e
e - child
f - child

From this you can see that you can’t call private methods outside their own class, and protected methods are automatically virtual methods that override the parents. Public is available as an access specifier for completeness, but not necessary.

If you want a good Javascript book, I got a lot out of Secrets of the Javascript Ninja.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *