javascript - function decorator reassigning hoisted inner function without eval -


i'm playing function decorators. i'd have way decorate functions without having function declared.

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"); 

i want able call adddecorator anywhere inside g. i.e. @ top f hoisted above it's declaration.

in chrome's console following output:

f outer outer f outer outer f inner inner (hoisted) f inner inner (after declaration) before f inner inner (decorated) after f inner inner (undecorated) f outer outer  
  1. can done without eval?
  2. can adddecorator moved outside g? (not important)

you can both eliminate eval , move function outside of g if willing change convention slightly.

this have same effect called differently:

function adddecorator(decoration, fn) {     var decorated = around(decoration)(fn);     decorated.undecorate = function () {         return fn;     }     return decorated; }  f = adddecorator(mydecorator, f);  f = f.undecorate(); 

http://jsfiddle.net/8sut9/1/

if aren't willing change way called/used i'm afraid answer both of questions no.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -