gpt4 book ai didi

JavaScript 等效于 PHP __invoke

转载 作者:行者123 更新时间:2023-11-30 05:44:01 24 4
gpt4 key购买 nike

我正在开发一个小型框架(在 JS 中),出于美观和简单的原因,我想知道是否有一种方法可以实现类似于 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");

有什么想法吗?谢谢。

最佳答案

如果您准备使用 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

关于JavaScript 等效于 PHP __invoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19018912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com