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

Commit bceeff9

Browse files
committed
Approach to referencing this in ES5
1 parent fe8be00 commit bceeff9

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

es5/README.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,7 +1194,13 @@
11941194
this.firstName = 'Panda';
11951195
```
11961196
1197-
- When saving a reference to `this` use `_this`.
1197+
- Avoid referencing `this` and opt for scope binding instead. You typically
1198+
end up needing it when handling events in jQuery and this technique
1199+
encourages you to decauple event listeners from their handlers, makes the
1200+
code simpler and much easier to unit test.
1201+
1202+
If you really need to reference the `this` scope, never use `_this` but
1203+
`context` instead.
11981204
11991205
```javascript
12001206
// bad
@@ -1213,13 +1219,19 @@
12131219
};
12141220
}
12151221

1216-
// good
1222+
// bad
12171223
function() {
12181224
var _this = this;
12191225
return function() {
12201226
console.log(_this);
12211227
};
12221228
}
1229+
1230+
// good
1231+
_.bindAll( this, 'handleClickEvent' );
1232+
function() {
1233+
$( target ).on( 'click', this.handleClickEvent );
1234+
}
12231235
```
12241236
12251237
- Name your functions. This is helpful for stack traces.

0 commit comments

Comments
 (0)