我正在玩function decorators。我希望有一种方法可以轻松地修饰函数,而无需在声明函数的地方。
var __slice = [].slice;
this.around = function(decoration) {
return function(base) {
return function() {
var argv, callback, __value__,
_this = this;
argv = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
__value__ = void 0;
callback = function() {
return __value__ = base.apply(_this, argv);
};
decoration.apply(this, [callback].concat(argv));
return __value__;
};
};
};
f("from outer");
function f(a){
console.log("f OUTER",a);
};
f("from outer");
(function g(){
f("from Inner (hoisted)");
function addDecorator(decoration, fn) {
var decorated = around(decoration)(fn);
eval(fn.name + " = decorated");
decorated.unDecorate = function (){
eval(fn.name + " = fn");
}
}
function myDecorator(cb){
console.log("before");
cb();
console.log("after");
}
function f(a){
console.log("f INNER",a);
}
f("from Inner (after declaration)");
addDecorator(myDecorator, f);
f("from Inner (Decorated)");
f.unDecorate();
f("from Inner (Undecorated)");
})();
f("from outer");
我希望能够在addDecorator
内的任何地方拨打g
。即在f
悬挂在其上方的声明的顶部。
在Chrome的控制台中,我得到以下输出:
f OUTER from outer
f OUTER from outer
f INNER from Inner (hoisted)
f INNER from Inner (after declaration)
before
f INNER from Inner (Decorated)
after
f INNER from Inner (Undecorated)
f OUTER from outer
答案 0 :(得分:2)
如果您愿意稍微更改惯例,则可以消除eval
并将功能移至g
之外。
这将产生相同的效果,但调用方式略有不同:
function addDecorator(decoration, fn) {
var decorated = around(decoration)(fn);
decorated.unDecorate = function () {
return fn;
}
return decorated;
}
f = addDecorator(myDecorator, f);
f = f.unDecorate();
如果你不愿意改变它被调用/使用的方式,那么我担心你的两个问题的答案都是否定的。