doc: clarify this
in event listeners
this === eventEmitter or this === instance of EventEmitter, but it's this is not EventEmitter. PR-URL: https://github.com/nodejs/node/pull/20537 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com> Reviewed-By: Vse Mozhet Byt <vsemozhetbyt@gmail.com>
This commit is contained in:
parent
15f743165c
commit
2d945fd645
@ -43,21 +43,21 @@ myEmitter.emit('event');
|
|||||||
## Passing arguments and `this` to listeners
|
## Passing arguments and `this` to listeners
|
||||||
|
|
||||||
The `eventEmitter.emit()` method allows an arbitrary set of arguments to be
|
The `eventEmitter.emit()` method allows an arbitrary set of arguments to be
|
||||||
passed to the listener functions. It is important to keep in mind that when an
|
passed to the listener functions. It is important to keep in mind that when
|
||||||
ordinary listener function is called by the `EventEmitter`, the standard `this`
|
an ordinary listener function is called, the standard `this` keyword
|
||||||
keyword is intentionally set to reference the `EventEmitter` to which the
|
is intentionally set to reference the `EventEmitter` instance to which the
|
||||||
listener is attached.
|
listener is attached.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const myEmitter = new MyEmitter();
|
const myEmitter = new MyEmitter();
|
||||||
myEmitter.on('event', function(a, b) {
|
myEmitter.on('event', function(a, b) {
|
||||||
console.log(a, b, this);
|
console.log(a, b, this, this === myEmitter);
|
||||||
// Prints:
|
// Prints:
|
||||||
// a b MyEmitter {
|
// a b MyEmitter {
|
||||||
// domain: null,
|
// domain: null,
|
||||||
// _events: { event: [Function] },
|
// _events: { event: [Function] },
|
||||||
// _eventsCount: 1,
|
// _eventsCount: 1,
|
||||||
// _maxListeners: undefined }
|
// _maxListeners: undefined } true
|
||||||
});
|
});
|
||||||
myEmitter.emit('event', 'a', 'b');
|
myEmitter.emit('event', 'a', 'b');
|
||||||
```
|
```
|
||||||
|
Loading…
x
Reference in New Issue
Block a user