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

时间:2012-08-28 19:57:25

标签: javascript jquery string methods 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

3 个答案:

答案 0 :(得分:4)

<强>更新

这是我最后的工作答案:
在控制台中运行此代码后

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

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+']'));

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


你做了什么 不要使用EVAL

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

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

$('#foo').attr('id') === $('#foo')['attr']('id');

所以只需将字符串分开,并像使用对象属性一样使用方法名称,然后就可以了。

请记住: 当你拥有的是平衡锤时,一切都像是你的拇指。
Brendan Eich


如果有可能将多个参数传递给任何方法,那么你也可以按照这种方式进行工作(我认为 - 好吧:逻辑指令,但是它已经很晚了,而且逻辑很快被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]+']'));

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

答案 1 :(得分:1)

您应该使用以下方法之一:

  • 应用

    var result = function.apply(thisArg[, argsArray]);

  • 呼叫

    var result = fun.call(thisArg[, arg1[, arg2[, ...]]]);

以下是样本:

var Sample = function() {
var that = this;

this.sampleMethod = function() {
    return alert("Hello!");
};

this.sampleMethod2 = function(){

    that["sampleMethod"].apply(that);
};  
};

var objImpl = new Sample();

objImpl.sampleMethod2(); //you will get a message from 'sampleMethod()'

答案 2 :(得分:0)

Eval做你想做的事。然而,Eval是邪恶的,因为你不应该做你想做的事。

Why is using the JavaScript eval function a bad idea?

相关问题