Calling function inside object using bracket notation

…衆ロ難τιáo~ 提交于 2019-12-01 08:04:28

Use it like. You were very close

myobject["myfunction"]();

You can also do this

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

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"]();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!