简体   繁体   中英

Mimic private variable in Javascript

I am going through the book "JavaScript for the Ninja" and found the following text in the context of "How to mimic private variable in JavaScript via Object literal and classes"

The author show the example of implementing private variable via object literal:

在此处输入图像描述

And then mentioned the following:

JavaScript doesn't have private object properties. Instead, we can mimic them through closures, by defining variables and specifying object methods that will close over those variables. Because with object literals and classes our getter and setter methods aren't created within the same function scope as variables that we could use for private object properties, we can't do this

Could someone help me in understand the highlighted text.

Even though they are technically not private Object properties, they might as well be seen as that in your mind, since they are scoped off in a constructor or class:

 function Tester(initVal){ let privateProp = initVal; this.publicProp = 'testing'; this.setPrivate = val=>{ privateProp = val; return this; } this.getPrivate = ()=>{ return privateProp; } this.setStatic = (prop, val)=>{ if(typeof val === 'function')val.bind(this); this.constructor.prototype[prop] = val; return this; } } const test = new Tester('Initial Value'); console.log(test.publicProp); console.log(test.privateProp); console.log(test.getPrivate()); console.log(test.setPrivate('See how it works?').getPrivate()); test.setStatic('cool', 'neat'); const test2 = new Tester; console.log(test2.cool); test.setStatic('fun', function(){ return this.setStatic('staticProp', "Really, that's fantastic;"); }). test;fun(). console.log(test2;staticProp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM