我在 780 行代码 JS 脚本中的 3 个地方使用了 console.log() 和 console.dir() 语句。但是所有这些对于调试和发现使用应用程序时可能出现的问题都很有用。
我有一个打印内部应用程序状态的函数,即变量的当前值:
printData: function () {
var props = {
operation: this.operation,
operand: this.operand,
operandStr: this.operandStr,
memory: this.memory,
result: this.result,
digitsField: this.digitsField,
dgField: this.dgField,
operationField: this.operationField,
opField: this.opField
};
console.dir(props);
}
Run Code Online (Sandbox Code Playgroud)
我还有一个用闭包隐藏的不可变“常量”列表,但我可以使用名为 list() 的访问器方法打印它们;在控制台中。像这样的东西:
list: function () {
var index = 0,
newStr = "",
constant = '';
for (constant in constants) {
if (constants.hasOwnProperty(constant)) {
index = constant.indexOf('_');
newStr = constant.substr(index + 1);
console.log(newStr + ": " + constants[constant]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在调试中使用控制台的第三个地方是我的 init(); 函数,如果发生异常错误,我会在其中打印。
init: function (config) {
try {
this.memoryLabelField = global.getElementById(MEMORY_LABEL);
this.digitsField = global.getElementById(DIGITS_FIELD);
this.digitsField.value = '0';
this.operationField = global.getElementById(OPERATION_FIELD);
this.operationField.value = '';
return this;
} catch (error) {
console.log(error.message);
return error.message;
}
}
Run Code Online (Sandbox Code Playgroud)
正如我的问题所述,我应该在生产代码中保留这些控制台语句吗?
但是它们对于以后的代码维护非常有用。
让我知道你的想法。
由于这些不是持久日志,您不会从中获得太多好处。它也可以在每台个人计算机上运行,因为每个人都有自己的程序副本。如果你确实需要它,最好有一个可以切换此功能的变量。特别是如果您的目标是调试大量预先确定的内容。
客户端问题需要调试与服务器端略有不同。每个人都有自己的程序副本。Browser-JS 在客户端运行,您打开浏览器,您编写的所有代码都在完整的 repl 中,并且与服务器端相比,调试很容易,在服务器端您很可能无法访问该系统。它非常灵活,当您直接从自己的浏览器检查生产中的某些内容时,您可以覆盖它,而不会影响任何人。只需用这些控制台语句覆盖它并调试问题即可。
在服务器端编程中记录日志是个好主意。它提供了很多有用的信息并且是持久的。
| 归档时间: |
|
| 查看次数: |
1125 次 |
| 最近记录: |