简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM