PHP的JavaScript等价物
我正在开发一个小框架(用JS),出于美观和简单的考虑,我想知道是否有一种方法可以实现PHP“调用”之类的东西 例如:PHP的JavaScript等价物,javascript,php,class,Javascript,Php,Class,我正在开发一个小框架(用JS),出于美观和简单的考虑,我想知道是否有一种方法可以实现PHP“调用”之类的东西 例如: var myClass = function(config) { this.config = config; this.method = function(){}; this.execute = function() { return this.method.apply(this, arguments); } } var execC
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");
这是我能想到的最好的办法
更新版本(按op)
只需返回一个将构成公共界面的函数:
function myClass(config)
{
var pubif = function() {
return pubif.method.apply(pubif, arguments);
};
pubif.config = config;
pubif.method = function() { };
return pubif;
}
其余的代码保持不变。jsbin:据我所知不是这样,因为execCustom是函数myClass的一个实例,所以您可以使用main函数作为类的构造函数,或者作为执行的方法。我唯一能想到的就是定义一个包装函数,比如函数exec(execCustom){execCustom.\uu invoke()},其中u invoke被定义为execCustom(myClass)中的一个函数。谢谢Zack。是的,我想是的。。。如果我找不到一个更漂亮的方法,那么我想我会让它这样做。这很难看,但你的另一个选择是在构造函数中执行If()来检查配置是否是数组。如果是,请继续,否则请调用方法uu invoke。但是,这假设您永远不希望将数组传递给_invoke方法,并且始终希望将一个数组传递给构造函数(这也是非常讨厌的)非常有创意!我想现在不可能再访问“config”和“method”值了?我更新了您的代码以便访问属性:您看到该代码有任何问题吗?非常感谢!在我的代码中,console.log(execcustominstanceof myClass)//false。您应该注意到,execCustom不是myClass实例。是的,我知道这一区别。代码仍然很有用。谢谢
function myClass(config)
{
var pubif = function() {
return pubif.method.apply(pubif, arguments);
};
pubif.config = config;
pubif.method = function() { };
return pubif;
}