简体   繁体   中英

How to use a Javascript Function to name Variables?

I'd like to be able to create variables using a function, something like:

function createVar(a,b){
    var [a]name[b];
}

So if I call the function createVar(prefix,suffix) I'd end up with a variable named prefixnamesuffix .

You can't create a local variable that way, but you can create properties with strings.

function createVar(obj, a, b)
{
   obj[a+'name'+b] = foo;
}
function createVar(a, b, value) {
    // declare the variable on current context(default is window),
    // and set value, default is undefined
    this[a + 'name' + b] = value;
}

use as:

createVar('a', 'b');
// variable anameb now is declare, but it's value is undefined
console.log(anameb); // -> undefined

createVar('prefix', 'suffix', 'optional');
// variable prefixnamesuffix now is exist in window
console.log(prefixnamesuffix); // -> 'optional'

or:

var obj = {};
createVar.call(obj, 'pre', 'suf', 'defValue');
// variable prenamesuf is now exist in obj, but not exist in window
console.log(obj.prenamesuf); // -> 'defValue'
console.log(prenamesuf); // ReferenceError: prenamesuf is not defined

This IS possible - sort of as it IS a bit tricky.

This all begins by understanding the scope of a variable. Let's look at a basic, simple example:

var myvar = 'I see';

This creates a varaible, at a basic level named myvar that you can access such as alert(myvar); which will, in this case alert "I see".

What this really does is create a property on the window object. Thus, var myvar = 'I see'; is the same as window['myvar'] = 'I see'; .

Complex objects can also be created in this manner.

Some more examples:

window['fred'] = 'howdy fred';// create fred property
var regularfred = 'howdy fred'; // create regularfred property
window['town'] = {}; // create town object
window['town']['george'] = 'georgetown'; //create town.george property
alert(fred + ":" + regularfred); // alerts "howdy fred:howdy fred"
alert(fred == regularfred);// alerts true
alert(this['town']['george']);// alerts "georgetown"

function createvar(a, b) {
    this[a + 'name' + b] = "fredling";
    alert(this[a + 'name' + b]);// alerts "fredling"
    alert(window[a + 'name' + b]);// alerts "fredling"
}
var hi = 'hi';
var lo = 'loook';
createvar(hi, lo);
alert(this[hi + 'name' + lo]);// alerts "fredling"

Requisit working example on this: http://jsfiddle.net/pGWZN/

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