Javascript code as a variable

Well, that might sound a little crazy, but listen to me :)

I would like to do the following in javascript:

define START_OF_EVERY_FUNCTION = "try {" define END_OF_EVERY_FUNCTION = "} catch () {}" function TEST () { START_OF_EVERY_FUNCTION // rest of function END_OF_EVERY_FUNCTION } 

Basically, can I define a list of javascript strings (code) and include them as above? I am looking for a technique compared to the comments about whether this is a good idea or not, or to discuss the packaging of all functions in a try / catch block.

I know about eval (), but I don't think you can use expressions like the ones above.

+4
source share
6 answers

This may be silly, but you can define the main function and run other functions through it by passing them.

 var execute = function(func){ alert('before'); func(); alert('after'); }; function sayHi(){ alert('hi there'); } execute(sayHi); 

As requested, an example with passing arguments.

 var execute = function(func){ alert('before'); var ret = func.apply(null, Array.prototype.slice.call(arguments, 1)); alert('after'); }; function saySomething(sayWhat){ alert(sayWhat); } execute(saySomething,'hey there'); 
+4
source

This is not valid in JavaScript.

+1
source

You can extend the function prototype:

 Function.prototype.tryThis = function() { try { this(); }catch(ex){ alert('Caught '+ex); }; }; function tryIt() { alert('Inside tryIt');throw "My Error from tryIt"; } tryIt.tryThis(); 
+1
source

You need to learn aspect-oriented programming for JavaScript. You can create hooks to enter and exit functions. Tools like JSUnit do this, for example.

0
source

I think you can do this with the "new Function" operator. I never used it myself, since I'm not crazy crazy, but I believe that you can pass it a string that will be eval uate and used as the body of the function. You can also get the code for each function by calling myFunction.toString() . So it will be something like this:

 var functionsToMessUp = ['myFunc1', 'myFunc2']; for (var i = 0; i < functionsToMessUp.length; ++i) { var theFunc = window[functionsToMessUp[i]]; // assuming they're in global scope window[functionsToMessUp[i]] = new Function( START_OF_EVERY_FUNCTION + theFunc.toString() + END_OF_EVERY_FUNCTION ); } 

Now this will almost certainly not work - the parameters and other things will be taken into account there, and I don’t even think how the new Function constructor works, but if you really want to go this way (which I really do not recommend), then this can be good starting point for you.

0
source

Maybe something like this?

 function tryCatch(callback) { try { callback(); } catch() {} } var myFunction = function() { // do some stuff }; tryCatch(myFunction); 
0
source

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


All Articles