Gil*_*tes 4 javascript oop coding-style private jslint
据我所知,在 JavaScript 中没有好的解决方案来创建私有成员。这里描述的解决方案效率不高,因为私有成员成为对象的一部分,而不是原型,因此需要更多内存。
所以,我决定只使用 Python 实践 - 用前导下划线标记私有内容,让其他人知道 makred 属性或方法不打算从外部使用。
但是有一个著名的代码质量工具 - JSLint,它建议不要使用前导或尾随下划线。
这背后的原理是什么?这只是代码风格的建议还是下划线会导致更严重的问题?如果它只是 JS 社区的代码风格约定,它有多强?
JSLint 是一个很好的工具,但它表达了对其作者风格的编码实践的意见。在此处了解这些偏好是什么。使用前导下划线/下划线对 JavaScript 解析器没有害处,该工具被编程为将其视为不良约定并警告您不要使用它。如果使用前导下划线是您的偏好并且有意义,请使用它们。
如果您在使用以下划线/下划线开头的标识符时不想在 JSLint 中看到警告,则 JSLint 中有一个设置可以对您隐藏这些警告。像这个例子一样包装你不想被评估的代码,你不会看到警告:
/*jslint nomen: true */
var _gaq = {};
/*jslint nomen: false */
Run Code Online (Sandbox Code Playgroud)
This is true if you're having code evaluated from a file, but if you're on the JSLint website there is an option to "Tolerate... dangling _ in identifiers" that removes the warning as well.
Please note that doing this may cause issues in how JSHint parses the file. Take a look at this link showing JSLint vs JSHint in relation to that flag. But if you're going to go by the JSLint standard mixing JSHint can cause a bit of confusion.
Private variables don't exist in JavaScript without using closures, but it's not a pattern needed for every project execution. If you want to know more about closures in JavaScript check out Ben Nadel's wonderful blog post and NetTuts+
| 归档时间: |
|
| 查看次数: |
4043 次 |
| 最近记录: |