I’ve always learned that Javascript didn’t support private fields. You could use closures as a ‘language hack’ to keep information private but it is not at the same level of simplicity:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Animal = (function () { | |
var name; | |
function Animal(theName) { | |
name = theName; | |
} | |
return Animal; | |
}()); |
In the example above the privateVar field is not directly accessible.
As I switched to TypeScript a long time ago, I didn’t care too much and happily used the private keyword there.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
private name: string; | |
constructor(theName: string) { | |
this.name = theName; | |
} | |
} |
Of course this was just a TypeScript hack and in the generated Javascript, the field was still accessible.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var Animal = /** @class */ (function () { | |
function Animal(name) { | |
this.name = name; | |
} | |
return Animal; | |
}()); |
More recently I switched to a different syntax in TypeScript to specify private fields:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
#name: string; | |
constructor(name: string) { | |
this.#name = name; | |
} | |
} |
What I wasn’t aware of that this became the default way that private fields are specified in Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Animal { | |
#name | |
constructor(name) { | |
this.#name = name; | |
} | |
} |
Cool!