假设我正在测试一个函数,并且我希望我的函数仅在测试未通过时才显示有关其自身的一些信息。
我不想在保存数据供以后使用时改变函数的流程。
function foo(input){
//normal work of the function
//save the value of variable A
//normal work of the function
//save the value of variable B
//normal work of the function
}
这将是一个测试
fooTest(){
var condition = foo();
//display variable A and B depending on the value of the condition
}
我该怎么做?
就我而言,我正在测试函数,并且希望它们在测试失败时向我展示它们的值(value)。如果它们没有失败,我不想在屏幕上显示信息。
最佳答案
您可能希望在函数执行后使用闭包来保留变量的值。
function set(A, B) {
// perform your operation
let a = A;
let b = B;
// The nested scope will remember the parent's scope
const getA = function() { return a; }
const getB = function() { return b; }
return { getA, getB };
}
var obj = set(10, 20);
console.log(obj.getA());
console.log(obj.getB());
关于javascript - 如何保存函数的信息以供以后使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54919190/