11

MDN says that "Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DataCloneError exception."

Why does copying a function object emit an error with structuredClone()?

2
  • What are you looking for? Probably the only answer you can get is "That's just how JavaScript works" with a reference to the ECMAScript spec. Commented May 4, 2022 at 15:06
  • @Samathingamajig I want to know what potential problems are there when copying a function. I believe that there is a clear reason why structured clones do not copy functions. Commented May 4, 2022 at 15:09

1 Answer 1

13

If you read on MDN/structuredClone, it says

Exceptions

DataCloneError DOMException

  • Thrown if any part of the input value is not serializable.

For why functions are not serializable, see here: Why is a function not serializable?

From what I understand of those answers, the TL;DR is that it's because a function can be converted to a string, but the variables/functions referenced in the function that are out of scope would cause issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.