Object.prototype不要直接使用,代码规范
1、不要直接调用 Object.prototype
的方法,比如 hasOwnProperty
, propertyIsEnumerable
, 和 isPrototypeOf
.
// bad console.log(object.hasOwnProperty(key)); // good console.log(Object.prototype.hasOwnProperty.call(object, key)); // best const has = Object.prototype.hasOwnProperty; // 在模块作用域内,缓存查找一次。 /* or */ import has from 'has'; // ... console.log(has.call(object, key));
2、用对象展开操作符浅复制对象,优先于Object.assign
。使用对象剩余操作符来获得一个省略某些属性的新对象。
// very bad const original = { a: 1, b: 2 }; const copy = Object.assign(original, { c: 3 }); // `original` 是可变的 ಠ_ಠ delete copy.a; // so does this // bad const original = { a: 1, b: 2 }; const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } // good const original = { a: 1, b: 2 }; const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
3、解构 Destructuring
当访问和使用对象的多个属性时,请使用对象解构。eslint: prefer-destructuring
jscs: requireObjectDestructuring
为什么?解构可以在你建这些属性的临时引用时,为你节省时间。 // bad function getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`; } // good function getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`; } // best function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`; }
数组解构
const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr;
4、使用对象解构来实现多个返回值,而不是数组解构。jscs: disallowArrayDestructuringReturn
// bad function processInput(input) { // 那么奇迹发生了 return [left, right, top, bottom]; } // 调用者需要考虑返回数据的顺序 const [left, __, top] = processInput(input); // good function processInput(input) { // 那么奇迹发生了 return { left, right, top, bottom }; } // 调用者只选择他们需要的数据 const { left, top } = processInput(input);
5、永远不要在一个非函数代码块(if
、while
等)中声明一个函数,把那个函数赋给一个变量代替。浏览器允许你这么做,但是它们都以不同的方式解析。 eslint: no-loop-func
// bad if (currentUser) { function test() { console.log('Nope.'); } } // good let test; if (currentUser) { test = () => { console.log('Yup.'); }; }
原文链接: http://www.css88.com/archives/8345