Kyle Adams Kyle Adams - 6 months ago 15
Javascript Question

Extending self container functions Javascript

Consider the following example:

var FunctionName = () => {
return {
helloWorld() { console.log("hello world"); }
}
};

var OtherFunctionName = () => {
return {
goodBye() { console.log("Bye Bye"); }
}
};


Assuming I haven't done something syntactically wrong in the above, how would I extend
FunctionName
in
OtherFunctionName
so that
OtherFunctionName
has access to
helloWorld
??

Because the code base may contain an ES6 class, is it possible to use the same method to extend said class into a self contained function to get access to the classes methods?

So:

var FunctionName = () => {
return {
helloWorld() { console.log("hello world"); }
}
};

class OtherClass {
goodBye() { console.log("Bye Bye"); }
};


In this case
FunctionName
would extend
OtherClass
to get access to
goodBye
. Is that possible

What are the methods to extend a self contained function on a self contained function.

and

What are the methods to extend a class on a self contained function

Is this where Object.assign or lodashes
._extend
would come in handy?

Answer

You can, if you want to use the prototypes, use Object.create. It allows you to create a object with a certain prototype. Because you don't want to change everything to 'Property descriptors', you could combine it with Object.assign:

var FunctionName = () => {
  return Object.assign(Object.create(OtherClass.prototype), {
    helloWorld() { console.log("hello world"); }
  })
};

If you'd want to support factory functions and classes, this would do:

var FunctionName = () => {
  return Object.assign(
    OtherClass.prototype ? Object.create(OtherClass.prototype) : OtherClass(), {
    helloWorld() { console.log("hello world"); }
  })
};
Comments