2013-09-26 59 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; 
} 

代碼的其餘部分保持不變。