是否可以使用字符串从对象调用方法?

Aus*_*ust 5 javascript string methods jquery eval

是否可以使用字符串从对象调用方法?

var elem = $('#test');             //<div id="test"></div>
var str = "attr('id')";  

//This is what I'm trying to achieve
  elem.attr('id');                 //test

//What I've tried so far  
  elem.str;                        //undefined
  elem.str();                      //Object [object Object] has no method 'str'
  var fn = eval(str);              //attr is not defined
  eval(elem.toString()+'.'+str);   //Unexpected identifier

//Only solution I've found so far, 
//but is not an option for me 
//because this code is in a function 
//so the element and method call
//get passed in and I wouldn't know
//what they are
  eval($('#test').attr('id'));     //test
Run Code Online (Sandbox Code Playgroud)

Eli*_*gem 4

更新

这是我最终的有效答案:
在控制台中运行此代码后

theMethod = 'attr("id","foo")'.match(/^([^(]+)\(([^)]*)\)/);
jQuery('#post-form')[theMethod[1]].apply(jQuery('#post-form'),JSON.parse('['+theMethod[2]+']'));
Run Code Online (Sandbox Code Playgroud)

post-form 元素现在有了新的 ID,没有任何问题。这适用于采用多个参数、单个参数或根本没有参数的方法。回顾:

theMethod = theInString.match(/^\.?([^(]+)\(([^)]*)\)/);
//added \.? to trim leading dot
//made match in between brackets non-greedy
//dropped the $ flag at the end, to avoid issues with trailing white-space after )
elem[theMethod[1]].apply(elem,JSON.parse('['+theMethod+']'));
Run Code Online (Sandbox Code Playgroud)

这是我能想到的最安全、最可靠的方法,真的


无论你做什么,都不要使用 EVAL

var theMethod = 'attr(\'id\')';
//break it down:
theMethod = theMethod.match(/^([^(]+)\(.*?([^)'"]+).*\)$/);
//returns ["attr('id')", "attr", "id"]
elem[theMethod[1]](theMethod[2]);//calls the method
Run Code Online (Sandbox Code Playgroud)

这与任何对象使用的基本原理相同(请记住,函数在 JS 中都是独立的对象,而且 jQuery 对象也是对象)。这意味着可以按照与属性完全相同的方式访问方法:

$('#foo').attr('id') === $('#foo')['attr']('id');
Run Code Online (Sandbox Code Playgroud)

因此,只需将字符串分开,然后像使用对象属性一样使用方法名称即可。

请记住:当您只有评估锤时,所有东西看起来都像您的拇指。
布伦丹·艾奇


如果有可能将多个参数传递给任何方法,您也可以解决这个问题(我认为 - 好吧:逻辑决定,但已经很晚了,逻辑现在被 Gin 打败得非常糟糕) :

theMethod = theMethod.match(/^([^(]+)\(([^)]+)\)$/);
//["attr('id','foo')", "attr", "'id','foo'"] --> regex must now match quotes, too
elem.theMethod[1].apply(elem,JSON.parse('['+theMethod[2]+']'));
Run Code Online (Sandbox Code Playgroud)

这会将您正在处理的任何元素/对象的方法应用于其自身,因此不会更改调用者上下文(this仍将指向方法内的对象),并且它传递将传递给被调用方法的参数数组。

  • 您无法在逗号上可靠地分割参数,因为参数中可能还有其他逗号。`'func(greet("Elias", "嗨,你好吗"), /(.*?),.*/)'` (2认同)