如何在Javascript中包装一个函数? [英] How do I wrap a function in Javascript?

查看:158
本文介绍了如何在Javascript中包装一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要的功能之一就是能够轻松地包装一个带有Try {} Catch {}块的函数,以便对该函数的所有调用都将自动具有将调用我的全局日志记录方法的错误处理代码。 (为了避免使用try / catch块在任何地方污染代码)。

然而,这稍微超出了我对Javascript的低级功能的理解,即.call和.apply方法以及this关键字。



我根据Prototype的Function.wrap方法编写了这段代码:

  Object.extend(Function.prototype,{
TryCatchWrap:function(){
var __method = this;
return function() {
try {__method.apply(this,arguments)} catch(ex){ErrorHandler.Exception(ex);}
}
}
});

这是这样使用的:



<$ p $ a $ b $ a $ b $ c $ a

$ b $ alert $(1 / e); $ p $
}

var fn2 = DoSomething.TryCatchWrap();
fn2(1,2,3,4);

该代码完美无缺。它打印出6,然后调用我的全局错误处理程序。

我的问题是...当我包装的函数位于一个对象中时,它使用this运算符?我有点担心,因为我打电话。应用程序,传递的东西,恐怕这可能会打破某些东西。

解决方案

个人而不是污染内建对象,我会去装饰技术:

  var makeSafe = function(fn){
返回函数(){
try {
return fn.apply(this,arguments);
} catch(ex){
ErrorHandler.Exception(ex);
}
};
};

您可以像这样使用它:

  function fnOriginal(a){
console.log(1 / a);
};

var fn2 = makeSafe(fnOriginal);
fn2(1);
fn2(0);
fn2(abracadabra!);

var obj = {
method1:function(x){/ * do something * /},
method2:function(x){/ * do something * /}
};

obj.safeMethod1 = makeSafe(obj.method1);
obj.method1(42); //原始方法
obj.safeMethod1(42); //安全方法

//让我们完全覆盖一个方法
obj.method2 = makeSafe(obj.method2);

但是,如果您确实想修改原型,可以这样写:

  Function.prototype.TryCatchWrap = function(){
var fn = this; //因为我们在函数本身上调用它
//让我们从makeSafe()复制其余部分
return function(){
try {
return fn.apply(this,参数);
} catch(ex){
ErrorHandler.Exception(ex);
}
};
};

明显的改进是参数化makeSafe(),以便您可以指定在catch块中调用哪个函数。


I'm writing a global error handling "module" for one of my applications.

One of the features I want to have is to be able to easily wrap a function with a Try{} Catch{} block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting the code everywhere with try/catch blocks).

This is, however, slightly beyond my understanding of the low-level functioning of Javascript, the .call and .apply methods, and the "this" keyword.

I wrote this code, based on Prototype's Function.wrap method:

Object.extend(Function.prototype, {
  TryCatchWrap: function() {
    var __method = this;
    return function() {
            try { __method.apply(this, arguments) } catch(ex) { ErrorHandler.Exception(ex); }
    }
  }
});

Which is used like this:

    function DoSomething(a, b, c, d) {
        document.write(a + b + c)
        alert(1/e);
    }

    var fn2 = DoSomething.TryCatchWrap();
    fn2(1, 2, 3, 4);

That code works perfectly. It prints out 6, and then calls my global error handler.

My question is... Will this break something when the function I'm wrapping is within an object, and it uses the "this" operator? I'm slightly worried since I'm calling .apply, passing something there, I'm afraid this may break something.

解决方案

Personally instead of polluting builtin objects I would go with a decorator technique:

var makeSafe = function(fn){
  return function(){
    try{
      return fn.apply(this, arguments);
    }catch(ex){
      ErrorHandler.Exception(ex);
    }
  };
};

You can use it like that:

function fnOriginal(a){
  console.log(1/a);
};

var fn2 = makeSafe(fnOriginal);
fn2(1);
fn2(0);
fn2("abracadabra!");

var obj = {
  method1: function(x){ /* do something */ },
  method2: function(x){ /* do something */ }
};

obj.safeMethod1 = makeSafe(obj.method1);
obj.method1(42);     // the original method
obj.safeMethod1(42); // the "safe" method

// let's override a method completely
obj.method2 = makeSafe(obj.method2);

But if you do feel like modifying prototypes, you can write it like that:

Function.prototype.TryCatchWrap = function(){
  var fn = this; // because we call it on the function itself
  // let's copy the rest from makeSafe()
  return function(){
    try{
      return fn.apply(this, arguments);
    }catch(ex){
      ErrorHandler.Exception(ex);
    }
  };
};

Obvious improvement will be to parameterize makeSafe() so you can specify what function to call in the catch block.

这篇关于如何在Javascript中包装一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆