Mention .bind for methods passed as values

This commit is contained in:
solarcloud7 committed 2026-07-12 01:29:24 -04:00
1 parent 5e1455c3d6
commit 0e8fe54ae3
1 file changed
+4
+4
View File
@@ -459,6 +459,7 @@ The send and handle methods depend on `this`, so call them directly on the conne
Extracting one into a variable, destructuring it, or passing it as an unbound callback drops the receiver and the method later throws when called with `this === undefined` (for example `Cannot read properties of undefined (reading 'sendRequest')`).
A type cast around a method that is invoked directly still retains its receiver, but storing or passing the cast result is an unsafe extraction.
When possible, cast the arguments or result instead of the method so the binding remains obvious.
When a method has to be passed as a value, use `.bind()` to fix its receiver first — most commonly when registering handlers.
```js
// Broken: the extracted method loses its `this` binding and crashes when called.
@@ -467,6 +468,9 @@ send("controller", new messages.Frobnicate({ foo: "bar" }));
// Correct: call it bound on the connection object and cast the arguments/result if needed.
this.instance.sendTo("controller", new messages.Frobnicate({ foo: "bar" }));
// Correct: bind the receiver when passing a method as a value, such as a handler.
this.instance.handle(messages.Frobnicate, this.handleFrobnicate.bind(this));
```
For classes with `static type = "request"` the send method is async and returns a promise that resolves to the response data received from the target it was sent to, or rejects with an error if the request failed.