Be possible is, now if this is a good thing I no longer know, I understand why this might sound interesting but the reading of the code can later be impaired. Anyway, you can do this by following one of the templates below.
First, when calling the function next()
or prev()
or any other with parentheses, you are not assigning the variable to the function itself, but rather the result of that function, so to assign a function to a variable you should not place the final parentheses of it. Another important point, these functions belong to a Jquery object, so you cannot call them directly, to access a Jquery function without calling it you can do the following $.fn.next
now you have the function stored in the variable action
but you can’t call her that $('.container').action
, this because action is not a property of Jquery to be called from an object of the same, you need to call the function stored in action and create the context of the object needed to be executed, you can do this using the property call
that the functions have, so your final code would look like this:
const action = $(this).hasClass('avancar') ? $.fn.next : $.fn.prev;
action.call($('.container'));
Another way to do something similar to what you want is to use an if ternary to directly call the next and Prev functions of the object, it would be something like the following:
$(this).hasClass('avancar') ? $('.container').next() : $('.container').prev();
Good answer, but use the
call
for something like this is killing ants with bazooka, right? -D– Luiz Felipe
This is true kkk, had forgotten the brackets to do this, your answer is surely more elegant :D
– mauricio-andre
That nothing, elegant really is wearing
if
/else
no invention of fashion, rsrs. D– Luiz Felipe
Thank you @Luizfelipe and Mario . I ended up opting for Luiz’s reply taking into account Maurício’s own comment. Here I still perform more actions than the example above, then it seemed to me more sense to save in a variable, but I understand your point. Thank you very much!
– Vinicius Verner