Skip to content

Commit edf8c6d

Browse files
jasnelldanielleadams
authored andcommitted
doc: add note about uncloneable objects
Signed-off-by: James M Snell <[email protected]> PR-URL: #36534 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: Franziska Hinkelmann <[email protected]>
1 parent f0a9c53 commit edf8c6d

File tree

1 file changed

+43
-5
lines changed

1 file changed

+43
-5
lines changed

‎doc/api/worker_threads.md‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -547,11 +547,6 @@ const otherChannel = new MessageChannel();
547547
port2.postMessage({port:otherChannel.port1 }, [ otherChannel.port1 ]);
548548
```
549549

550-
Because the object cloning uses the structured clone algorithm,
551-
non-enumerable properties, property accessors, and object prototypes are
552-
not preserved. In particular, [`Buffer`][] objects are read as
553-
plain [`Uint8Array`][]s on the receiving side.
554-
555550
The message object is cloned immediately, and can be modified after
556551
posting without having side effects.
557552

@@ -606,6 +601,49 @@ The `ArrayBuffer`s for `Buffer` instances created using
606601
transferred but doing so renders all other existing views of
607602
those `ArrayBuffer`s unusable.
608603

604+
#### Considerations when cloning objects with prototypes, classes, and accessors
605+
606+
Because object cloning uses the [HTML structured clone algorithm][],
607+
non-enumerable properties, property accessors, and object prototypes are
608+
not preserved. In particular, [`Buffer`][] objects will be read as
609+
plain [`Uint8Array`][]s on the receiving side, and instances of JavaScript
610+
classes will be cloned as plain JavaScript objects.
611+
612+
```js
613+
constb=Symbol('b');
614+
615+
classFoo{
616+
#a =1;
617+
constructor(){
618+
this[b] =2;
619+
this.c=3;
620+
}
621+
622+
getd(){return4}
623+
}
624+
625+
const{port1, port2 } =newMessageChannel();
626+
627+
port1.onmessage= ({data }) =>console.log(data);
628+
629+
port2.postMessage(newFoo());
630+
631+
// Prints:{c: 3 }
632+
```
633+
634+
This limitation extends to many built-in objects, such as the global `URL`
635+
object:
636+
637+
```js
638+
const{port1, port2 } =newMessageChannel();
639+
640+
port1.onmessage= ({data }) =>console.log(data);
641+
642+
port2.postMessage(newURL('https://example.org'));
643+
644+
// Prints:{}
645+
```
646+
609647
### `port.ref()`
610648
<!-- YAML
611649
added: v10.5.0

0 commit comments

Comments
(0)