这与这个问题有些关联,但我不是在寻找有关JavaScript最佳实践的资源,而是需要你的实际建议。
我将从自己的列表开始。如果您确定建议不具有争议性,可以发布回答或直接编辑问题。
下面是我的建议:
- always use
var
- capitalize names of constructor functions - and nothing else
- use
===
for comparison - use explicit casts for primitives, e.g.
Number()
,String()
,Boolean()
- check for primitive types with
typeof
- check for object types with
instanceof
check for built-in object types with
Object.prototype.toString()
to avoid cross-frame issues, e.g.Object.prototype.toString.call(obj) === '[object Array]'
check
this
in constructors, e.g.function MyObject() { if(!(this instanceof arguments.callee)) throw new Error('constructor called with invalid `this`'); // [...] }
use anonymous functions for namespacing to not pollute the global scope, e.g.
(function() { var noGlobalVar = 'foo'; // [...] })();
check
hasOwnProperty()
infor..in
loops - don't assume that no one messed with the prototypes- don't use
for..in
loops to iterate over elements of arrays or array-like objects