2

I want to set a variable to either .prev() or .next(), for example:

   if(x == y)
       var shift = '.prev()';
   else
       var shift = '.next()';

   $("li.active").removeClass('active')shift.addClass('active');

I could probably get it working with eval() however it's a security hazard.

Am I missing something obvious?

0

1 Answer 1

5

Every property of an object can be accessed by using bracket notation [spec].
foo.bar() is the same as foo['bar']():

if(x == y)
   var shift = 'prev';
else
   var shift = 'next';

// or a shorter and nicer way: 
// var shift = x == y ? 'prev' : 'next';

$("li.active").removeClass('active')[shift]().addClass('active');
Sign up to request clarification or add additional context in comments.

4 Comments

shift declaration is out of scope, no?
@Madbreaks: No. JavaScript only has function scope.
Interesting. Ok, but how about var shift = x === y ? prev : next; :)
@Madbreaks: Yep, I was just suggesting that ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.