如何设置特定的变量名?

时间:2018-12-21 15:39:33

标签: javascript dictionary global-variables

是否有可能在重复功能(对象编程)中设置特定的变量名?

我需要重用此函数,并且每次使用时都需要特定的变量名(函数属性+ a)。

function test(test)
{
    var a + test = 'test text';
    console.log(atest);
}

test('test');

我需要变量atest才能产生'test text'

2 个答案:

答案 0 :(得分:0)

您想要的是一个有范围的命名空间,例如myVariables用作字典,例如

// this prevents keys like `hasOwnProperty` from being pre-defined on namespace
var myVariables = Object.create(null);

function test(name) {
  myVariables['a' + name] = 'test text';
}

test('test');
console.log(myVariables.atest);

答案 1 :(得分:0)

这确实是一个不好的编程,但是答案是:

  window['a'+'test'] = 'test text';
  
  console.log(atest);