If I copy code into a closure like this
(function(){
var private1 = {},
private2 = {},
publik;
publik.get(object){
private1[object.name] = object;
};
window.publik = publik;
}())
publik.get({
// API
name: 'name_foo',
functionA: function(){
// I can not access private2 in here
},
functionB: function(){}
})
Is there a way the API can work, so that the functionA and functionB can have access to private 2 inside the closure.
They will be copied into the closure, so the copied version should have access to it. That is why I made the closure and put private1 and private2 together like that.
The written version ( not the copied version ) of the object throws an error in jslint and my guess is that this is becasue it breaks scope rules.
The function argument ( not parameter ) is an un-named variable in the global scope and has no access to the closure.
( until is is copied into it 🙂
Would it work if I made private1 and private 2 the same object say…just private…and then accessed it using this keyword.
I would prefer to keep them separate however.
Your code has syntax errors and get seems to be better named as set. Also, your code doesn’t seem to be specific to browsers, so better to use the more generic global object than the specific window object.
Consider something like:
The publik.set method has access to private1 and private2 through a closure, you can access them through privileged methods as explained by Douglas Crockford in his article Private Members in JavaScript. Extending the above, it might be: