开发者

How best to invoke arbitrary methods on arbitrary objects in javascript?

开发者 https://www.devze.com 2023-02-13 21:28 出处:网络
I would like to be able to call arbitrary methods on arbitrary objects. Something like: function applyArbitraryMethod( method, args ) {

I would like to be able to call arbitrary methods on arbitrary objects. Something like:

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

applyArbitraryMethod( 'Object.method', args );

which doesn't work, but this does:

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

appl开发者_Python百科yArbitraryMethod( 'Object', 'method', args );

BUT, now I would like to be able to call

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

with an arbitrary number of descendents on Object. My current solution is:

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

But I'm wondering if there's a more straightforward way of achieving the same goal.


This should work:

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


You could do this:

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 );
}

but as the throw lines shows, this could easily go wrong, and i'd recommend you to go about this another way


Try this:

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));
}


I did not end up finding a more straightforward solution. So my current correct answer sits at:

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

精彩评论

暂无评论...
验证码 换一张
取 消