Why the creators of the TypeScript compiler did not turn the class into JavaScript closure, which makes variables private

Why did the typescript compiler leave to convert classes to closures to provide data hiding?

class Person {
    public name: string;     
    private password: string;

    constructor(name:string,password: string) {
        this.name = name;       
        this.password= password;
    }
} 
let p = new Person("mihir","!@#123");

In the above code, I saved the password as a private variable. Therefore, we should not directly access this variable. The following code is compiled from typescript code. the password variable remains publicly available since I don't have an access modifier in javascript.

var Person = (function () {
    function Person(name,password) {
        this.name= name;
        this.password= password;
    }
    return Person;
})();

var p = new Person("mihir","!@#123");

According to the following code, using a trailing variable can be protected from the outside.

var Person = (function () {
    var _pass;     
    function Person(name,password) {       
        this.name = name;        
        _pass = password;
    }
    return Person;
})();   

We understand that data encapsulation is applicable in typescript, and the purpose of typescript is to write more productive code than javascript.

typescript ? , .

javacsript typescript. , ?

+4
1

, , , typescript, javascript .

1) private

var Person = (function () {
    var _pass;     
    function Person(name,password) {       
        this.name = name;        
        _pass = password;
    }

    Person.prototype.getPassword = function() {
        return _pass;
    }

    return Person;
})();

var p1 = new Person("mihir","!@#123");
var p2 = new Person("khushbu","!@#345");
console.log(p1.getPassword()); // '!@#345'
console.log(p2.getPassword()); // '!@#345'

_pass static.since _pass , , , . . .

2)

var Person = (function () {

    function Person(name, password) {       
        var _pass = password;
        this.name = name;
        this.getPassword = function () {
            return _pass;
        }
    }
    return Person;
})();

var p1 = new Person('mihir','!@#123');
var p2 = new Person('khushbu','!@#456');
console.log(p1.getPassword()); // '!@#123'
console.log(p2.getPassword()); // '!@#456'

- . . javascript.

, typescript .

javascript "private" , , " ". javascript.

+4

Source: https://habr.com/ru/post/1686304/


All Articles