我们如何确定被调用的变量函数的名称?
我有一个函数充当测试实用函数来设置我的测试用例。根据测试传递给测试实用函数的参数,某些子函数可能会执行,也可能不会执行。有时这些子功能会失败,我需要知道哪一个失败了,但不知道该怎么做。在其他语言中,我在这里会使用反射。这是一个选择吗?
这是我们正在做的事情的抽象示例:
exports.test_util_func = function(params, callback){
//initialize the functions
var a = function(callback){
...
//response might be "{status:400, body: {error: {...} } }"
callback(error, response);
}
var b = function(callback){
...
callback(error, response);
}
//determine what functions to run
var functions_to_run = [];
if(params.a) functions_to_run.push(a);
if(params.b) functions_to_run.push(a);
async.series(functions, function(error, responses){
if(error) throw new Error(error);
for(var i in responses){(function(response){
//verify that we received a 200 success status from the server
//if we didn't, capture the error
if(response.status!==200){
console.log(response.body);
console.log(i);
//HELP NEEDED HERE - how do we capture better than the function iteration so we know what actually failed? Ideally, we would have: "reflective call()
throw new Error(i+": "+JSON.stringify(response.body));
}
})(responses[i]);}
})
}
编辑:下面的文章中可能有一些我们可以使用的东西,但我想通过使用 __prototype 信息一定有一些更简单的方法:Get variable name. javascript "reflection"
最佳答案
我找到了一种解决方法,可以让我继续使用此模式,但并不完全可靠。创建函数后,我们创建 use 将名称存储在函数原型(prototype)中。
理想的情况仍然是能够引用变量名称本身。
最终代码示例:
exports.test_util_func = function(params, callback){
//initialize the functions
var a = function(callback){
...
//response might be "{status:400, body: {error: {...} } }"
callback(error, response);
}
a.prototype.name = "a";
var b = function(callback){
...
callback(error, response);
}
a.prototype.name = "b";
//determine what functions to run
var functions_to_run = [];
if(params.a) functions_to_run.push(a);
if(params.b) functions_to_run.push(a);
async.series(functions, function(error, responses){
if(error) throw new Error(error);
for(var i in responses){(function(response){
//verify that we received a 200 success status from the server
//if we didn't, capture the error
if(response.status!==200){
console.log(functions.map(function(func){return func.prototype.name})[i]);
console.log(response.body);
}
})(responses[i]);}
})
}
关于javascript - 在 javascript 中使用反射来获取失败时测试函数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29766119/