Javascript dynamically invoke object method from string

那年仲夏 提交于 2019-11-26 05:26:41

问题


Can I dynamically call an object method having the method name as a string? I would imagine it like this:

var FooClass = function() {
    this.smile = function() {};
}

var method = \"smile\";
var foo = new FooClass();

// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();

回答1:


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

foo[method]();



回答2:


Properties of objects can be accessed through the array notation:

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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/9854995/javascript-dynamically-invoke-object-method-from-string

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