How to create privacy using bind ()

I pass the object literal to a structure method called supportP() . This object literal has the special property _p , which means that its members are private. From with in an object literal can be obtained through this._p . However, when I pass the object literal to the "external" volume, I do not copy _p . Now it was closed by inaction. To access _p from public member methods, I bind them to the original object using bind() so that they still have access to _p through this .

Will this work? Are there any other questions? Some feedback is required before I checked it.

Below are the relevant snippets.

 /*$A.supportP ** ** ** */ $A.supportP = function (o, not_singleton) { var oo key; SupportList[o.Name] = {}; if (not_singleton) { // ignore this section } else { // *look here - isFunc returns true if a function for (key in o) { if ((key !== '_p') && (isFunc(o[key])) { oo[key] = o[key].bind(o); } else if (key !== '_p') { oo[key] = o[key]; } else { // private (_p) - anything to do here? } } return oo; } }; /*$A.test ** ** ** */ var singleton_object = $A.supportP({ _p: 'I am private', Name: 'test', publik_func: function () { // this will refer to this object so that it can access _p // this._p is accessible here due to binding } }, false); 
+1
source share
1 answer

Will this work?

Yes, you can access the "private" property through this._p .

Are there any other questions?

You are cloning an object. However, the method on it does not have access to it - it is tied to the "old" object, whose properties do not reflect changes in the copy. I'm not sure if this is by design or by accident.


For strict privacy, you will need to use closures with local variables. Properties can never be closed.

 var singleton_object = (function() { var _p = 'I am private'; // local variable return { Name: 'test', publik_func: function () { // this will refer to this object so that it can access the properties // _p is accessible here due to closure, but not to anything else } }; }()); // immediately-executed function expression 

Another solution using two different objects (one hidden) that are passed to the structure method:

 function bindPrivates(private, obj) { for (var key in obj) if (typeof obj[key] == "function") obj[key] = obj[key].bind(obj, private); return obj; } var singleton_object = bindPrivates({ p: 'I am private' }, { Name: 'test', publik_func: function (_) { // this will refer to this object so that it can access "public" properties // _.p, a "private property" is accessible here due to binding the private // object to the first argument } }); 
+1
source

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


All Articles