Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  28] [ 4]  / answers: 1 / hits: 21210  / 16 Years ago, sat, february 28, 2009, 12:00:00

If you want to use global functions and variable dynamically you can use:



window[functionName](window[varName]);


Is it possible to do the same thing for variables in the local scope?



This code works correctly but currently uses eval and I'm trying to think of how else to do it.



var test = function(){
//this = window
var a, b, c; //private variables

var prop = function(name, def){
//this = window
eval(name+ ' = ' + (def.toSource() || undefined) + ';');

return function(value){
//this = test object
if ( !value) {
return eval('(' + name + ')');
}
eval(name + ' = value;')
return this;
};

};

return {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via to methods
return [a,b,c];
}
};
}();

>>>test
Object
>>>test.prop
undefined
>>>test.a
function()
>>>test.a()
1 //returns the default
>>>test.a(123)
Object //returns the object
>>>test.a()
123 //returns the changed private variable
>>>test.d()
[123,2,3]

More From » scope

 Answers
46

No, like crescentfresh said. Below you find an example of how to implement without eval, but with an internal private object.



var test = function () {
var prv={ };
function prop(name, def) {
prv[name] = def;
return function(value) {
// if (!value) is true for 'undefined', 'null', '0', NaN, '' (empty string) and false.
// I assume you wanted undefined. If you also want null add: || value===null
// Another way is to check arguments.length to get how many parameters was
// given to this function when it was called.
if (typeof value === undefined){
//check if hasOwnProperty so you don't unexpected results from
//the objects prototype.
return Object.prototype.hasOwnProperty.call(prv,name) ? prv[name] : undefined;
}
prv[name]=value;
return this;
}
};

return pub = {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via two methods
//This is a case where 'with' could be used since it only reads from the object.
return [prv.a,prv.b,prv.c];
}
};
}();

[#99909] Tuesday, February 24, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;