views:

65

answers:

2

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'
}
}

A: 

You would just use: ....

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

Since you declared the vars before the if statement, they will be available from within it.

If you are worried about scope, if it's within an object, you would use: alert(this.var1);

liquidleaf
But he needs to access by variable's name...
ItzWarty
i want to access it with its string name 'var1'
coure06
+1 cause -4 seems too harsh here. it may not answer the question, but the answer is not day and night either to the question.
Anurag
+2  A: 

Try something like:

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

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

};

Alternatively, this may be a bit more inline 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
macek