Python decoder with javascript

I want to do the following:

I have a function that warns something:

myfunction = function(foobar) { alert(foobar); }; 

Now I want to decorate it so that:

 decorate = function(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; }; 

So, I can write:

 myfunction = decorate(myfunction); 

And then myfunction will do a regular + log in the console.

How can I make it work with Javascript?

+6
source share
2 answers

Yes, you can. And actually, you have, your implementation works just fine: Live example | a source

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

I would recommend using function declarations rather than function expressions, though:

 function myfunction(foobar) { alert(foobar); } function decorate(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; } var result = decorate(myfunction); result("Hi there"); 

And if you want to create a more general version, look at apply ( MDN | spec ) and the arguments pseudo-array ( MDN | spec ): Live example | a source

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

There are several things in this version:

  • Allows you to include a callback as an argument to one central decorate function.

  • Allows you to specify a "context" ( this value) that will be used when calling the callback.

  • Saves the value of this when calling both the original and (if you do not supply context ) a callback.

... which is convenient for decorating objects (sometimes called methods).

+10
source

More general arguments and apply:

 function myfunction(foobar) { alert(foobar); } function decorate(callback) { return function() { callback.apply(null, arguments); console.log(arguments); }; } var result = decorate(myfunction); result("Hi there"); 
+2
source

Source: https://habr.com/ru/post/914821/


All Articles