Javascript dynamically invoke object method from string

廉价感情. 提交于 2019-11-26 17:29:27

if the name of the property is stored in a variable, use []

foo[method]();

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"

method can be call with eval eval("foo." + method + "()"); might not be very good way.

When we call a function inside an object, we need provide the name of the function as a String.

var obj = {talk: function(){ console.log('Hi') }};

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!