Brian Morton
Brian Morton

Reputation: 97

Assign multiple functions to class in ES6

I'd like to have one master class with the methods derived from many other functions attached to it. So say I have

class MasterObject {
   method1...,
   method2...,
   etc...
}

Using ES6, id like to import these functions to assign to the MasterClass as methods. So I have tried something like this:

function setUpObj (...fns) {

    class MasterObj {
         constructor (...args) {
              Object.assign(this, args)
         }
    }

    return new MasterObj(fns)
 }

 let master = setUpObj(square, add, divide)

 master.square(1,2) 

When I do this, the methods are not actually assigned to the object (I am assuming they are assigned to the this, but not as methods). Clearly I don't understand how prototypical inheritance works, so if you can explain it in terms of ES6 classes that would really help me a lot.

Relevant: https://gist.github.com/allenwb/53927e46b31564168a1d ES6 Class Multiple inheritance

Upvotes: 1

Views: 616

Answers (2)

TbWill4321
TbWill4321

Reputation: 8676

You need to have Object.assign take an object, so it has an idea of what to call the functions.

You also need to directly modify the prototype so that the functions are bound to the class instead of the this.

function setUpObj (fns) {

    class MasterObj { }

    Object.assign( MasterObj.prototype, fns );

    return new MasterObj()
 }

 let master = setUpObj({ square, add, divide })

 master.square(1,2) 

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161627

Object.assign accepts an object containing properties to copy over. In your case, you are passing it an array, which means you will have square as master[0](1, 2). If you want them named, you'll need to pass them with names, e.g.

function setUpObj (fns) {

    class MasterObj {
         constructor (args) {
             Object.assign(this, args);
         }
    }

    return new MasterObj(fns)
}

let master = setUpObj({square, add, divide})

master.square(1, 2);

that said, this setup seems a little strange since you are redeclaring the class every time. Perhaps something like this would be clearer:

function setUpObj (fns) {
    class MasterObj {
    }

    Object.assign(MasterObj.prototype, fns);

    return MasterObj;
}

let MasterObjWithFunctions = setUpObj({square, add, divide})

let master = new MasterObjWithFunctions();

master.square(1, 2) 

Upvotes: 2

Related Questions