How to Implement Inheritance and Copy Objects in Object-Oriented JavaScript?

Estimated read time 1 min read

To implement inheritance in JavaScript, use the prototype property. The prototype is an object that provides shared properties and methods to instances of an object. You can create a new object that inherits from an existing object by setting the new object’s prototype to the existing object.

let obj1 = {
    x: 10,
    y: 20

let obj2 = Object.create(obj1);

console.log(obj2.x);  // 10

To copy an object, you can use the Object.assign method which copies the values of all enumerable properties of one or more source objects to a target object.

let obj1 = {x: 10, y: 20};
let obj2 = Object.assign({}, obj1);
console.log(obj2);  // {x: 10, y: 20}

Or you can use spread operator ...

let obj1 = {x: 10, y: 20};
let obj2 = {...obj1};
console.log(obj2);  // {x: 10, y: 20}

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply