javascript 在Javascript中动态调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26328294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:49:02  来源:igfitidea点击:

Call function dynamically in Javascript

javascriptnode.js

提问by Cxodael

I want to dynamically call a function from a string like "User.find". A script would call the function find() in the object User if the function exists. Here's what I tried:

我想从像“User.find”这样的字符串动态调用一个函数。如果函数存在,脚本将调用对象 User 中的函数 find() 。这是我尝试过的:

 var User = {};
 User.find = function(){
     return 1;
 }

 var input = 'User.find';
 var some_data_array = {name: 'John Doe'};
 var method = input.toString().split('.');
 var nameObj = method[0].substring(0,1).toUpperCase() + method[0].substring(1);
 var methodToCall = method[1];

 nameObj.call(methodToCall, some_data_array);

But it always returns:

但它总是返回:

 nameObj.call(methodToCall, some_data_array);
 TypeError: Object User has no method 'call'

Any idea? I can't use window since it is a node.js problem, the script is not executed in the browser.

任何的想法?我不能使用 window 因为它是一个 node.js 问题,脚本没有在浏览器中执行。

回答by SLaks

You're completely misunderstanding call().

你完全误会了call()

call()lets you call a method with a different this.

call()允许您使用不同的this.

You want to get as property by name:

您想按名称获取属性:

object[methodName](arg1, arg, ...);

回答by sudipto

You actually can achieve this. You first would need to get the scope, where your namespace/function/object is defined.

你实际上可以做到这一点。您首先需要获取scope,其中定义了您的命名空间/函数/对象。

For example, in your code I would assume its window.

例如,在您的代码中,我假设它的window.

So, a little modification of your code would produce the desired result:

因此,对您的代码稍作修改就会产生所需的结果:

var User = {};
User.find = function(x){
    alert(x);
}

 var input = 'User.find';
 var some_data_array = {name: 'John Doe'};
 var method = input.toString().split('.');
 var nameObj = global[method[0]];
 var methodToCall = method[1];

 nameObj[methodToCall](some_data_array.name);

Mark the use of global[]. This is where it starts.

标记使用global[]. 这就是它开始的地方。

[edited] * Modified code to use globalinstead of windowas being used in nodejs.

[编辑] * 修改代码以使用global而不是windownodejs.

回答by slevy1

There are a couple of ways to get the desired result. In this case it is very simple to just use an anonymous function, as follows, passing in the string parameter contained in objName.name:

有几种方法可以获得所需的结果。在这种情况下,只使用匿名函数非常简单,如下所示,传入包含在objName.name中的字符串参数:

var f = function(oName){
  if (oName == 'John Doe') {
     return 1;
  }   
 };


 var objName = {name: 'John Doe'};
 
console.log( f( objName.name ) );

If the OP prefers to use an object's call method, the following code also will suffice:

如果 OP 更喜欢使用对象的调用方法,以下代码也足够了:

var myObj = {
  myFunc: function() {
    if (this.name == 'John Doe') {
      return 1;
    }
  }
}

var objName = {
  name: 'John Doe'
};

console.log(myObj.myFunc.call(objName));

A couple of things to note. myObj calls its method myFunc() passing in the object parameter objName. The purpose of thisin the method is to read the property name, possessing that ability because of being bound to the object objName.

有几点需要注意。myObj 调用其方法 myFunc() 并传入对象参数 objName。方法中this的目的是读取属性name,因为绑定到对象 objName 而具有该能力。

回答by EvilZebra

What you want to do is access the global object.

您要做的是访问全局对象。

This should work:

这应该有效:

var User = {};
User.find = function(){
    return 1;
}

var input = 'User.find';
var some_data_array = {name: 'John Doe'};
var method = input.toString().split('.');
var nameObj = method[0].substring(0,1).toUpperCase() +method[0].substring(1);
var methodToCall = method[1];

"use strict";
var global = (1,eval)("this");
alert(global[nameObj][methodToCall](some_data_array));