#privatevariables
Explore tagged Tumblr posts
Link
#python#privatevariables#pythonvariables#programs#pythonlanguage#dataanalytics#datascience#analytics#data
0 notes
Text
Private Variables in JavaScript (New Syntax)
Private variables have always been possible in JavaScript, but before the new syntax they required somewhat cumbersome steps to use. For example:
function Car(name, hp) { const privateVariable = 'test1'; this.name = name; this.hp = hp; // Note this will not appear in inherited copies of this object. this.print = function() { console.log(`${this.name} (${this.hp}) - secret: ${privateVariable}`); } } const miata = new Car('miata', 155); console.log(miata.name); // miata console.log(miata.hp); // 155 console.log(miata.privateVariable); // undefined miata.print(); // miata (155) - secret: test1
Basically, private variables can be created in a scope that is no longer available and used via a closure. Now with the # syntax, this is much more straightforward:
class Car { #privateVariable = 'test1'; constructor(name, hp) { this.name = name; this.hp = hp; } print() { console.log(`${this.name} (${this.hp}) - secret: ${this.#privateVariable}`); } } const miata = new Car('miata', 155); console.log(miata.name); // miata console.log(miat2.hp); // 155 console.log(miata.privateVariable); // undefined miata.print(); // miata (155) - secret: test1
This is currently supported in Node.js 12 and Chrome by default. It will likely be in other browsers soon since it is now part of the JS standard.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2020/privateVariables.js
#private variables#private#object orientation#object oriented programming#es2020#javascript#programming#web development#app development
23 notes
·
View notes