2018年6月18日 星期一

Typescript public vs private vs protected

Public

Public class members are visible from within and outside the class

Private

Private are visible from within the class only

Protected

Protected are visible form the class and its descendents

However, for private keyword, it's actually not really as what it means.

for example of class Text in Typescript:

class Test {
public name: string;
private age: number;
protected ssn: string;
constructor(name: string, age: number, ssn: string) {
this.name = name;
this.age = age;
this.ssn = ssn;
}
}

After convert it into Javascript:

var Test = /** @class */ (function () {
function Test(name, age, ssn) {
this.name = name;
this.age = age;
this.ssn = ssn;
}
return Test;
}());

For translated Javascript file, it cannot prevent variable accessed from outside. (public variable name is declared same as private variable ssn)

In order to set ssn into private, it should be something like:

var Test = (function() {
var _ssn;
function Test(name, age, ssn) {
this.name = name;
this.age = age;
_ssn = ssn;
}
return Test;
}());

So when use the private keyword in TypeScript, keep in mind that it just suggests it's nice and not access it directly, but actually generates public getter and setter methods instead.

沒有留言:

張貼留言