首页 > 解决方案 > 如何保存有关功能的信息以供以后使用?

问题描述

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

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

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

}

我该怎么做?

就我而言,我正在测试功能,如果测试失败,我希望它们向我展示它们的价值。如果他们没有失败,我不想在屏幕上显示信息。

标签: javascript

解决方案


您可能希望在函数执行后使用闭包来保留变量的值。

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());


推荐阅读