Javascript从字符串动态调用对象方法

IT技术 javascript oop dynamic methods invoke
2021-01-15 07:43:01

我可以动态调用具有方法名称作为字符串的对象方法吗?我会想象它是这样的:

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();
5个回答

如果属性的名称存储在变量中,请使用 []

foo[method]();
如果要从类中的另一个方法执行方法,请使用 this['methodName']()。
2021-03-23 07:43:01
在函数中使用变量对我不起作用:const genericResolver = ( table, action , values ) => { return Auth.isAuthenticated() .then(() => { return eval(table).findAll()
2021-03-29 07:43:01
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FooClass'其他人收到这个丑陋的错误吗?
2021-04-08 07:43:01

可以通过数组符号访问对象的属性:

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

当我们在对象内部调用函数时,我们需要提供函数名作为字符串。

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

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
为您的代码提供一些注释总是有帮助的,这样就可以脱离上下文理解它。
2021-03-25 07:43:01
添加了一些评论。谢谢!
2021-03-25 07:43:01

方法可以用 eval 调用 eval("foo." + method + "()"); 可能不是很好的方法。

在我的情况下有用,foo{ fields: [{ id: 1 }] }methodfields[0]?.id,但我不得不()从你提出的答案中删除
2021-03-25 07:43:01

我想在这里留下一个例子。例如; 我想在提交表单时调用动态检查方法。

<form data-before-submit="MyObject.myMethod">
    <button type="submit">Submit</button>
</form>
$('form').on('submit', function(e){

    var beforeSubmit = $(this).attr('data-before-submit');

    if( beforeSubmit ){

       params = beforeSubmit.split(".");
       objectName = params[0];
       methodName = params[1];

       result = window[objectName][methodName]($(this));

       if( result !== true ){
           e.preventDefault();
       }

    }

});

var MyObject = {
    myMethod = function(form){
        console.log('worked');
        return true;
    }
};