4

If i have a function defined inside some object as in :

var myobject={
myfunction:function(){//mycode here}
}

usually you can access the function using:

myobject.myfunction()

but what if i want to use

myobject["myfunction"]

trying so , actually the function did not get called , how can i call the function using brackets notation ?

1
  • Just a side note - Using bracket notation you can also have function names which are invalid otherwise. So myobject["my function"]() will work but myobject.my function() using dot notation will not.
    – RBT
    Oct 16, 2017 at 1:48

2 Answers 2

15

Use it like. You were very close

myobject["myfunction"]();

You can also do this

var myfuncname="myfunction";
myobject[myfuncname]();
0
2

The two forms

myobject.myfunction;

and

myobject["myfunction"];

are equivalent as long as you only use a fixed string to access the member (using a computed value is a different matter, then you must use the second form). Both lines result in the function-object-member myfunction which you can assign to a variable if you like, and calling that:

var myfunc = myobject.myfunction;
myfunc();

Note that assigning it to the variable breaks the this variable, so you might not want to do that if you're doing OOP.

And as you noted, calling a function means adding () with an argument list afterwards, it doesn't matter that the function is acquired through an expression, so either:

myobject.myfunction();

or

myobject["myfunction"]();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.