Jens Modvig
Jens Modvig

Reputation: 183

How to copy properties of one class to another in javascript, including methods

I have two classes A and B that work independently of each other, but sometimes I want to create them together, so that the functions in A call the functions in B. This can easily be done by extending B from A and thereby overriding the methods, this however doesn't allow me to create B independently of A. Instead I want to copy all of the properties and methods. I have tried using Object.assign the following example illustrates the problem.

class A {
    myFunc() {
        throw 'I have not been created yet'
    }   
}
class B {
    myFunc() {
        console.log(`it's all good now!`)
    }
}

let a = new A();
let b = new B();
Object.assign(a, b)

// explicitly copying the method works
//a.myFunc = b.myFunc;

a.myFunc();

The question is: is there a way to copy all of the methods without doing it explicitly?

Upvotes: 3

Views: 2546

Answers (1)

BlueWater86
BlueWater86

Reputation: 1817

You can iterate the property names of B's prototype and assign them to the instance of a excluding the constructor in the following way:

class A {
    myFunc() {
        throw 'I have not been created yet'
    }   
}
class B {
    myFunc() {
        console.log(`it's all good now!`)
    }
}


let a = new A();
let b = new B();
//Object.assign(a, b)

for (const prop of Object.getOwnPropertyNames(B.prototype).filter(prop => prop !== "constructor"))
  a[prop] = B.prototype[prop]

// explicitly copying the method works
//a.myFunc = b.myFunc;

a.myFunc();

Upvotes: 2

Related Questions