mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-11 15:04:52 +09:00
Mention .bind for methods passed as values
This commit is contained in:
1 parent
5e1455c3d6
commit
0e8fe54ae3
1 file changed
+4
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user