Convert string to variable name in JavaScript

后端 未结 11 1695
无人及你
无人及你 2020-11-22 02:59

I’ve looked for solutions, but couldn’t find any that work.

I have a variable called onlyVideo.

\"onlyVideo\" the string gets passe

11条回答
  •  温柔的废话
    2020-11-22 03:40

    It can be done like this

    (function(X, Y) {
      
      // X is the local name of the 'class'
      // Doo is default value if param X is empty
      var X = (typeof X == 'string') ? X: 'Doo';
      var Y = (typeof Y == 'string') ? Y: 'doo';
      
      // this refers to the local X defined above
      this[X] = function(doo) {
        // object variable
        this.doo = doo || 'doo it';
      }
      // prototypal inheritance for methods
      // defined by another
      this[X].prototype[Y] = function() {
        return this.doo || 'doo';
      };
      
      // make X global
      window[X] = this[X];
    }('Dooa', 'dooa')); // give the names here
    
    // test
    doo = new Dooa('abc');
    doo2 = new Dooa('def');
    console.log(doo.dooa());
    console.log(doo2.dooa());

提交回复
热议问题