javascript - 如何保存函数的信息以供以后使用?

标签 javascript

假设我正在测试一个函数,并且我希望我的函数仅在测试未通过时才显示有关其自身的一些信息。

我不想在保存数据供以后使用时改变函数的流程。

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/

相关文章:

javascript - Thorax.js Collection View 不渲染模型属性

javascript - 从element指令中的routeProvider获取参数

javascript - 如何在包装时保留 grunt 任务参数

javascript - Internet Explorer 不支持 JavaScript?

javascript - 点击函数内的ajax请求干扰执行

JavaScript:如何在用户选择注销时关闭所有子窗口?

javascript - HTML 表格标题显示不正确

javascript - 松散打字的优点是什么?

javascript - 调整输入复选框的填充并与按钮垂直对齐

javascript - 带有状态的 Angular UI Router View