我正在開發一個小框架(在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");
任何想法?謝謝。
jsbin:http://jsbin.com/ESOLIce/1/edit?js,console – lepe
據我所知,因爲execCustom是函數myClass的一個實例,因此您要麼使用主函數作爲構造函數爲班級,或作爲一種方法來執行。我唯一能想到的就是定義一個包裝函數,就像函數exec(execCustom){execCustom .__ invoke()},其中__invoke被定義爲execCustom(myClass)中的一個函數。 –
謝謝扎克。是的,我認爲是這樣的......如果我找不到更好的方法去做,那麼我想我會像這樣離開它。 – lepe