2013-09-26 37 views
1

我正在开发一个小框架(在JS中),并且出于审美原因和简单性,我想知道是否有可能实现类似PHP“__invoke”的方法。JavaScript等效的PHP __invoke

例如:

var myClass = function(config) { 
    this.config = config; 
    this.method = function(){}; 
    this.execute = function() { 
     return this.method.apply(this, arguments); 
    } 
} 
var execCustom = new myClass({ wait: 100 }); 
execCustom.method = function() { 
    console.log("called method with "+arguments.length+" argument(s):"); 
    for(var a in arguments) console.log(arguments[a]); 
    return true; 
}; 
execCustom.execute("someval","other"); 

希望的方式来执行:

execCustom("someval","other"); 

任何想法?谢谢。

+0

jsbin:http://jsbin.com/ESOLIce/1/edit?js,console – lepe

+0

据我所知,因为execCustom是函数myClass的一个实例,因此您要么使用主函数作为构造函数为班级,或作为一种方法来执行。我唯一能想到的就是定义一个包装函数,就像函数exec(execCustom){execCustom .__ invoke()},其中__invoke被定义为execCustom(myClass)中的一个函数。 –

+0

谢谢扎克。是的,我认为是这样的......如果我找不到更好的方法去做,那么我想我会像这样离开它。 – lepe

回答

1

如果你准备用JS模式,您可以在以下方式做到这一点:

var myClass = function(opts) { 
      return function(){ 
      this.config = opts.config; 
      this.method = opts.method; 
      return this.method.apply(this, arguments); 
      }; 
     }; 


var execCustom = new myClass({ 
     config:{ wait: 100 }, 
     method:function() { 
      console.log("called method with "+arguments.length+" argument(s):"); 
      for(var a in arguments) console.log(arguments[a]); 
      return true; 
     }}); 

execCustom("someval","other"); 

jsbin

这是最好的方式,我能想到的

更新版本 (通过操作)

var myClass = function(opts) { 
     var x = function(){ 
      return x.method.apply(x, arguments); 
     }; 
     x.config = opts.config; 
     x.method = opts.method; 
     return x; 
    }; 


var execCustom = new myClass({ 
    config:{ wait: 100 }, 
    method:function() { 
     console.log("called method with "+arguments.length+" argument(s):"); 
     for(var a in arguments) console.log(arguments[a]); 
     return true; 
    }}); 

execCustom("someval","other"); 

jsbin

+0

非常有创意!我想现在不再可以访问“config”和“method”值了吗? – lepe

+0

我更新了代码以访问属性:http://jsbin.com/ESOLIce/13/watch?js,console 您是否看到该代码存在任何问题? – lepe

+0

是的,你的一个更好。 – caoglish

0

只返回一个函数,将形成公共接口:

function myClass(config) 
{ 
    var pubif = function() { 
    return pubif.method.apply(pubif, arguments); 
    }; 
    pubif.config = config; 
    pubif.method = function() { }; 

    return pubif; 
} 

代码的其余部分保持不变。