开发者

Javascript code as a variable

Ok, this may sound a bit crazy but hear me out :)

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 lines (code) and include them as above? I'm looking for a technique versus comments about whether this is a good idea or not or debate over wrapping all functions in a try/catch block.

I know about eval(),开发者_如何学运维 but I dont think you can eval statements like the above.


This might be goofy but you could define a master function and run other functions through it by passing them in.

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


That is not allowed in JavaScript.


You could 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();


You need to look into aspect oriented programming for JavaScript. You can create hooks for function entry and exit. Tools like JSUnit do this for example.


I think you can do this with the "new Function" operator. I've never used it myself, since I'm not clinically insane, but I believe you can pass it a string which it will evaluate and use as the function body. You can also get the code for each function by calling myFunction.toString(). So put together, it'd 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, the above almost certainly won't work - there's parameters and other things to take into consideration, and I don't even think that's how the new Function constructor works, but if you really want to go down this path (which I really don't recommend), then this might be a good starting point for you.


Maybe something like this?

function tryCatch(callback) {
  try {
    callback();
  } catch() {}
}

var myFunction = function() {
  // do some stuff
};

tryCatch(myFunction);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜