返回不起作用

时间:2018-04-13 11:13:24

标签: javascript



function trycatch(myfunction, name) {
  return function() {
    try {
      myfunction.apply(this, arguments);
    } catch (e) {
      console.log(e + name);
    }
  }
};
var rambo = {
  create: function(i, j) {
    return i
  },
  ramv: function() {
    aler("")
  }
};
for (var key in rambo) {
  if (typeof rambo[key] === 'function') {
    rambo[key] = trycatch(rambo[key], key);
  }
}

console.log(rambo.create(1))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我正在尝试将try catch应用到我的所有函数中,但似乎它们没有返回值,我错过了什么?

2 个答案:

答案 0 :(得分:5)

您从trycatch返回的功能没有return语句,因此它将始终返回undefined

您需要将通话的返回值返回apply

答案 1 :(得分:1)

您忘了在return中添加myfunction.apply(this, arguments);。目前trycatch返回函数,但该函数不返回任何内容,因此您还需要返回myfunction.apply(this, arguments);的函数值

&#13;
&#13;
function trycatch(myfunction,name) {
    return function() {
        try {
            return myfunction.apply(this, arguments);
        } catch(e) {
            console.log(e + name);
        }
    }
};
var rambo = { create: function(i,j) { debugger; return i},
ramv:function(){aler("")}
};
for (var key in rambo) {
 if( typeof rambo[key] === 'function' ) {
    rambo[key] = trycatch(rambo[key],key);
  }
}

console.log(rambo.create(1));
&#13;
&#13;
&#13;