Skip to content
This repository was archived by the owner on Aug 8, 2023. It is now read-only.

Commit ca645e0

Browse files
committed
Merge pull request #82 from mobify/js-self-vs-this
Javascript self vs bind(this)
2 parents d9f4d56 + 6e14339 commit ca645e0

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

javascript/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,51 @@ Prefer the short, more succinct version.
402402
Array.prototype.forEach.call(arguments, function(arg) { console.log(arg); });
403403
```
404404

405+
##Prefer `self` to `bind(this)`
406+
407+
```javascript
408+
// Good
409+
AiBot.prototype.answer = function(questionPromise) {
410+
var self = this;
411+
return questionPromise.then(function(question) {
412+
return self.determineResponse(question);
413+
});
414+
};
415+
416+
// Bad
417+
AiBot.prototype.answer = function(questionPromise) {
418+
return questionPromise.then(function(question) {
419+
return this.determineResponse(question);
420+
}.bind(this));
421+
};
422+
```
423+
424+
###Don't mix `bind(this)` and `self`
425+
426+
```javascript
427+
// Good
428+
UIService.prototype.addEventing = function(eventEmitter) {
429+
var self = this;
430+
431+
eventEmitter.on('someEvent', function() {
432+
self.uiController.once('uiEvent', function() {
433+
self.handleUiEvent();
434+
});
435+
});
436+
};
437+
438+
// Bad - too confusing
439+
UIService.prototype.addEventing = function(eventEmitter) {
440+
var self = this;
441+
442+
eventEmitter.on('someEvent', function() {
443+
this.uiController.once('uiEvent', function() {
444+
self.handleUiEvent();
445+
});
446+
}.bind(this));
447+
};
448+
```
449+
405450
##Method and promise chains
406451

407452
With method-chaining or promise APIs, we may have a long chain of

0 commit comments

Comments
 (0)