Skip to content

Commit

Permalink
Remove leading underscores for private properties
Browse files Browse the repository at this point in the history
- It follows [ES6 styleguide](https://github.com/airbnb/javascript#naming--leading-underscore)
- eslint plugin is configured this way : `'no-underscore-dangle': [2, { allowAfterThis: false }],`
  • Loading branch information
cmalard authored and jaylaw81 committed Sep 19, 2017
1 parent 69a2e17 commit 90df5b7
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions es5/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this._type || 'no type';
var type = this.type || 'no type';
return type;
}
Expand All @@ -727,7 +727,7 @@
console.log('fetching type...');
// set the default type to 'no type'
var type = this._type || 'no type';
var type = this.type || 'no type';
return type;
}
Expand Down Expand Up @@ -1178,18 +1178,21 @@
});
```
- Use a leading underscore `_` when naming private properties.
- Do not use trailing or leading underscores.
> Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won't count as breaking, or that tests aren't needed. tl;dr: if you want something to be “private”, it must not be observably present.
```javascript
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';

// good
this._firstName = 'Panda';
this.firstName = 'Panda';
```
- When saving a reference to `this` use `_this`.
- Don't save references to this. Use Function#bind.
```javascript
// bad
Expand All @@ -1208,13 +1211,20 @@
};
}

// good
// bad
function () {
var _this = this;
return function () {
console.log(_this);
};
}

// good
function () {
return function () {
console.log(this);
}.bind(this);
}
```
- Name your functions. This is helpful for stack traces.
Expand Down

0 comments on commit 90df5b7

Please sign in to comment.