Stann
Stann

Reputation: 13948

How can I invoke a member function using bracket notation?

var objectliteral = {
    func1:fn(){},
    func2:fn(){},
    .................
    funcn:fn(){}
}

I know I can invoke methods from that object literal using dot notation this:

objectliteral.func1();

But I would like to do that using array notation like this:

objectliteral[func1]. .... something something......

How do I do that? I know I can use apply or call methods - but I'm still don't quite get how they work.

Can I just do this?:

objectliteral[func1].apply();

RESOLUTION

based on answers:

objectliteral['func1']()

is all I need. Thanks guys.

Upvotes: 9

Views: 3455

Answers (6)

dontangg
dontangg

Reputation: 4809

You can do it like this:

var objectLiteral = {
    func1: function() { alert('func1'); },
    func2: function() { alert('func2'); }
};

// This does the same thing...
objectLiteral['func1']();

// As this does
objectLiteral.func1();

Upvotes: 3

Toby
Toby

Reputation: 1660

var func1 = 'func1'
objectLiteral[func1]();

Should get you working.

Upvotes: 1

Shurdoof
Shurdoof

Reputation: 1719

You can do objectliteral["func1"]();

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

user objectliteral["funct1"].apply() or objectliteral["funct1"]().

You can also use a variable to pass the function name

var funname = "funct1";
objectliteral[funname ]()

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You could try this:

objectliteral['func1']();

Upvotes: 1

thejh
thejh

Reputation: 45568

No, do this:

objectliteral['func1']();

You can also use a dynamic name:

var myfuncname='func1';
objectliteral[myfuncname]();

Upvotes: 15

Related Questions