是的你可以。事实上,你有,你的实现完美地工作:现场示例| 来源
var myfunction = function(foobar) { alert(foobar); };
var decorate = function(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; };
var result = decorate(myfunction);
result("Hi there");
不过,我建议使用函数声明而不是函数表达式:
function myfunction(foobar) {
alert(foobar);
}
function decorate(callback) {
return function(foobar) {
callback(foobar);
console.log(foobar);
};
}
var result = decorate(myfunction);
result("Hi there");
如果您想创建更通用的版本,请查看使用apply
( MDN | spec ) 和arguments
伪数组 ( MDN | spec ):Live example | 来源
function decorate(original, wrapper, context) {
return function() {
try {
original.apply(this, arguments);
}
catch (e) {
}
try {
wrapper.apply(context || this, arguments);
}
catch (e) {
}
};
}
function myFunction(arg1, arg2) {
alert("arg1 = " + arg1 + ", arg2 = " + arg2);
}
var newFunction = decorate(myFunction, function(arg1, arg2) {
console.log("arg1 = " + arg1 + ", arg2 = " + arg2);
});
newFunction(1, 2);
该版本做了几件事:
允许您将回调作为参数提供给一个中心decorate
函数。
this
让您有选择地提供调用回调时使用的“上下文”(值)。
保留this
调用原始回调和(如果您不提供context
)回调时的值。
...在装饰对象函数(有时称为方法)时很方便。