C. Ovidiu C. Ovidiu - 6 months ago 21
Javascript Question

jQuery: use dynamic object based on variable value

I have several objects and all of them have some methods that are called the same but do different things.

When I click a button, I want to call the
method, but the
object is different based on what button I clicked.

Here is a snippet

$btn.on('click', function(e){


var $trigger = $(this);
var objectName = $trigger.data('object');

if objectName is 'user', I want to call user.init(),
if it's 'product' I want to call product.init() and so on...
right now i get an error if I call like his


Is it possible to dynamically call an object like this ? I know it is for its properties and methods, but I din't find anything about this issue.

Thank you.


It's better to do mapping

var entities = {
    user: user,
    entity: entity

var objectName = $trigger.data('object');