这样写用到了es6里的Map对象,是不是更爽了?Map对象和Object对象有什么区别呢?
- 一个对象通常都有自己的原型,所以一个对象总有一个"prototype"键。
- 一个对象的键只能是字符串或者Symbols,但一个Map的键可以是任意值。
你可以通过size属性很容易地得到一个Map的键值对个数,而对象的键值对个数只能手动确认。
代码风格
常量大写
- //bad code
- const DAYS_IN_WEEK = 7;
- const daysInMonth = 30;
-
- const songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
- const Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];
-
- function eraseDatabase() {}
- function restore_database() {}
-
- class animal {}
- class Alpaca {}
-
- //better code
- const DAYS_IN_WEEK = 7;
- const DAYS_IN_MONTH = 30;
-
- const SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];
- const ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles'];
-
- function eraseDatabase() {}
- function restoreDatabase() {}
-
- class Animal {}
- class Alpaca {}
先声明后调用
- //bad code
- class PerformanceReview {
- constructor(employee) {
- this.employee = employee;
- }
-
- lookupPeers() {
- return db.lookup(this.employee, 'peers');
- }
-
- lookupManager() {
- return db.lookup(this.employee, 'manager');
- }
-
- getPeerReviews() {
- const peers = this.lookupPeers();
- // ...
- }
-
- perfReview() {
- this.getPeerReviews();
- this.getManagerReview();
- this.getSelfReview();
- }
-
- getManagerReview() {
- const manager = this.lookupManager();
- }
-
- getSelfReview() {
- // ...
- }
- }
-
- const review = new PerformanceReview(employee);
- review.perfReview();
-
- //better code
- class PerformanceReview {
- constructor(employee) {
- this.employee = employee;
- }
-
- perfReview() {
- this.getPeerReviews();
- this.getManagerReview();
- this.getSelfReview();
- }
-
- getPeerReviews() {
- const peers = this.lookupPeers();
- // ...
- }
-
- lookupPeers() {
- return db.lookup(this.employee, 'peers');
- }
-
- getManagerReview() {
- const manager = this.lookupManager();
- }
-
- lookupManager() {
- return db.lookup(this.employee, 'manager');
- }
-
- getSelfReview() {
- // ...
- }
- }
-
- const review = new PerformanceReview(employee);
- review.perfReview();
(编辑:ASP站长网)
|