Middle+
Which object copying methods can copy functions from one object to another?
sobes.tech AI
Answer from AI
In JavaScript, functions are first-class objects and can be copied along with objects in various ways. Here are the main methods of copying an object that preserve functions:
- Object.assign() — copies all enumerable own properties, including functions.
const obj = {
a: 1,
fn() { return this.a; }
};
const copy = Object.assign({}, obj);
console.log(copy.fn()); // 1
- Spread operator
{...obj}— also copies functions, as they are properties of the object.
const copy2 = {...obj};
console.log(copy2.fn()); // 1
-
JSON.stringify + JSON.parse — does not copy functions, as JSON does not support functions.
-
Manual copying of properties, including functions.
Thus, copying methods based on shallow copying of object properties (Object.assign, spread) preserve functions, while JSON serialization does not.