如何最好地在javascript中的任意对象上调用任意方法?

时间:2011-02-27 01:18:40

标签: javascript

我希望能够在任意对象上调用任意方法。类似的东西:

function applyArbitraryMethod( method, args ) {
    window[method].apply( this, args );
}

applyArbitraryMethod( 'Object.method', args );

哪个不起作用,但确实如此:

function applyArbitraryMethod( object, method, args ) {
    window[object][method].apply( this, args );
}

applyArbitraryMethod( 'Object', 'method', args );

但是现在我想打电话给

applyArbitraryMethod( 'Object.child.grandchild.method', args );

在Object上有任意数量的后代。我目前的解决方案是:

function applyArbitraryMethod( objects, args ) {
    objects = objects.split(/\./);
    var method = window;
    for( var i in objects ) method = method[objects[i]];
    method.apply( this, args );
}

但我想知道是否有更直接的方法来实现同样的目标。

4 个答案:

答案 0 :(得分:0)

这应该有效:

function applyArbitraryMethod(method, args) {
    method.apply(this, args);
}
applyArbitraryMethod(Object.method, args);

答案 1 :(得分:0)

你可以这样做:

function applyArbitraryMethod( method, args ) {
    var foo = window, bar = method.split('.');
    for(var i=0,fnName; fnName = bar[i];i++) {
      if(foo[fnName]) {
        foo = foo[fnName];
      }
      else {
       throw "whoopsidaisy, you made a typo :)";
      }
    }
    foo.apply( this, args );
}

但正如投掷线所示,这可能很容易出错,我建议你采取另一种方式

答案 2 :(得分:0)

试试这个:

function applyArbitraryMethod(objects) {
  if (!objects.match(/^[a-z0-9$_]+(?:\.[a-z0-9$_]+)*$/i)) 
    throw new Error("Invalid input!");
  eval(objects).apply(this, Array.prototype.slice.call(arguments, 1));
}

答案 3 :(得分:0)

我最终没有找到更简单的解决方案。所以我目前的正确答案是:

function applyArbitraryMethod( objects, args ) {
    objects = objects.split(/\./);
    var method = window;
    for( var i in objects ) method = method[objects[i]];
    method.apply( this, args );
}
相关问题