Accessing a class variable with a string name?

I have a class like this

$.fn.dimeBar = function(custom) {  
    var var1 = 'test1';  
    var var2 = 'test2';  
    if(sometest){  
        //how can i access var1 or var2 here by using string name of variables  
        //some thing like alert(this['var1']) --> should alert: 'test1'    
    }  
}

      

+2


a source to share


2 answers


Try something like:

$.fn.dimeBar = function(custom) {
  var options = {
    var1: 'test1',
    var2: 'test2'
  };

  if(sometest){
    var foo = 'var1';
    alert(options[foo]); // "test1"
  }

};

      



Alternatively, this can be a little more restrictive with the jQuery plugin development pattern

(function($){
  $.fn.dimeBar = function(options){

    // defaults
    options = $.extend({
      var1: "default",
      var2: "hello world"
    }, options);

    // debug options
    $.each(options, function(key, value){
      console.log(key+' is set to'+value);    
    });

  };
})(jQuery);

$('#foo').dimeBar({var2: "hello kitty"});

// console output
// var1 is set to default
// var2 is set to hello kitty

      

+2


a source


You would just use: ....

if (sometest) {alerts (var1); } ....



Since you declared vars before the if statement, they will be available internally.

If you are worried about the scope if it is inside an object, you should use: alert (this.var1);

-3


a source







All Articles