I have added following class in typescript
class Person {
private variable1;
public varibele2;
Person(){
this.variable1 = 'abc';
this.varibele2 = 'xyz';
}
public getVariable1(){
return this.variable1;
}
}
So When I compile the code using tsc , it generates the following code
var Person = (function () {
function Person() {
}
Person.prototype.Person = function () {
this.variable1 = 'abc';
this.varibele2 = 'xyz';
};
Person.prototype.getVariable1 = function () {
return this.variable1;
};
return Person;
}());
Since variable1 is private should not be accessible by the obj of that class(which is happening in typescript code).
Same behavior should be happened into transpiled es5 code(But not happening).
In above example's transpiled code I am creating object of the Person
var p = new Person();
console.log(p.variable1); // undefined
p.variable1 = 'abc1'; // setting value to variable 1
console.log(p.variable1); // 'abc1'
console.log(p.getVariable1()); // 'abc1'
In above code I should not be able to set or get the value of variable1.
var p = new Person();
console.log(p.getVariable1()); // 'undefined'
p.variable1 = 'abc1'; // setting value to variable1
console.log(p.getVariable1()); // 'abc1'
In above code , I am trying fetch the value using p.getVariable1() and I get undefined.Since value is already assigned in constructor of the class , it should be available through p.getVariable1()
var p = new Person();
console.log(p.variable2); // undefined
p.variable2 = 'xyz1'; // setting value
console.log(p.variable2);// 'xyz1'
In above code Variable2 should retrun 'xyz' but it's not. Once i assign value to it , it returns.
So Behavior of private and public variables are same in transpiled code and its very confusing. Its not returning the value which is assigned in constructor.
