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
}
我该怎么做?
就我而言,我正在测试功能,如果测试失败,我希望它们向我展示它们的价值。如果他们没有失败,我不想在屏幕上显示信息。
解决方案
您可能希望在函数执行后使用闭包来保留变量的值。
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());
推荐阅读
- android - 饼图显示剪切窗口属性更改未反映在使 videoview 全屏
- python - 计算模式同时忽略某些值
- apache - 使用 .htaccess 删除 URl 的某些部分?
- xamarin - 无法将类型“System.Windows.Input.ICommand”隐式转换为“Xamarin.Forms.Command”
- linux - dotnet restore 在配置有代理的 bitbucket 管道上失败
- c# - 在 Unity 中为我的 3d 模型添加动画?
- java - 这个数组“菜单”的作用是什么?我知道构造函数是如何工作的,但不确定为什么这个数组“菜单”与类名相同
- javascript - 单击视口中可见的按钮
- python - Python 中 f.seek() 的复杂性
- python - 如果满足 2 个条件,则将所有 numpy 数组值设置为 x