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.
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.
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.
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.
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.
No, do this:
objectliteral['func1']();
You can also use a dynamic name:
var myfuncname='func1';
objectliteral[myfuncname]();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With