Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 976
Stann Avatar asked Dec 17 '10 08:12

Stann


People also ask

How do you access an object's member using brackets notation?

Bracket notation is another way to access a property of an object. To use bracket notation, write the name of the object, followed by brackets [] . Inside the brackets, write the property name as a string. Bracket notation, unlike dot notation, can be used with variables.

Why do we use bracket notation?

We must use bracket notation whenever we are accessing an object's property using a variable or when the property's key is a number or includes a symbol or is two words with a space.

How do you use dot notation?

Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.

What notation do you use to access an object inside another object in JavaScript?

The alternate syntax for accessing object properties is known as bracket notation. In bracket notation, the object name is followed by a set of square brackets. Inside the square brackets, the property name is specified as a string.


2 Answers

No, do this:

objectliteral['func1']();

You can also use a dynamic name:

var myfuncname='func1';
objectliteral[myfuncname]();
like image 76
thejh Avatar answered Oct 13 '22 11:10

thejh


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();
like image 43
dontangg Avatar answered Oct 13 '22 12:10

dontangg