How to set a specific property for a private object

I want to be able to set the property to private by specifying the not notation path to the value. The difficulty is that this object is inside the closure, so I cannot access it directly to set the value in the usual way (for example, dot.notation.path = 'new value' ). It seems strange, but I cannot imagine the obvious way.

Example:

 // setter function function set(path, change){ var privateObject = { a: 'a', b: 'b', c: { d: 'd', e: 'e' } } privateObject[path] = change; return privateObject; } // execution var result = set('c.d', 'new value'); // desired result //{ // a: "a" // b: "b" // c: { // d: "new value", // e: 'e' // } //} // actual result //{ // a: "a" // b: "b" // c: { // d: 'd', // e: 'e' // } // cd: "new value" //} 

Working example:

JSFiddle Error Example ">

[Refresh] Alternative example:

JSFiddle working example ">

+4
source share
2 answers

You are really close, but parenthesis notation will not process points for you (it cannot - points are perfectly valid characters for property names). You have to do it yourself:

 function set(path, change){ var privateObject = { a: 'a', b: 'b', c: { d: 'd', e: 'e' } }, index, parts, obj; parts = path.split("."); obj = privateObject; if (parts.length) { index = 0; while (index < parts.length - 1) { obj = obj[parts[index++]]; } obj[parts[index]] = change; } return privateObject; } 

Live demo

I discarded this, it was not more efficient compared to older machines, and I did not investigate failure modes, but you understood: divide the path that you point to, then use each component of the page.

+5
source

This has nothing to do with private facilities or closures, and does a lot with what

 someObject['c.d'] 

not equivalent

 someObject['c']['d'] 

or

 someObject.cd 

You can create some construct that breaks your path string into. delimiter and applies the indexing operator iteratively to achieve the desired effect.

However, the whole exercise seems pointless. If you arbitrarily make changes to a private object from outside its scope, why not just add a mechanism to get the private object and change it directly?

+2
source

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


All Articles