Access a Function inside Factory Functions

Learn JavaScript Syntax: Objects | Codecademy

About the factory functions, why I can’t access a function parameter inside directly?
Example:

const robotFactory = (model) => {
  return {
    model,
    beep() {
      console.log('Beep Boop')
    }
  }
};

If I try:
robotFactory.beep();
I’ll get:

TypeError: robotFactory.beep is not a function

But if I try:

const tinCan = robotFactory('P-500');
tinCan.beep();

Works perfectly!

Why?

Hello, and welcome to the forums!

It doesn’t work when you try robotFactory.beep() because you’re not calling the factory function that returns the object with the beep() method.

It would work if you used robotFactory().beep() or robotFactory('P-500').beep() because you’d be calling robotFactory() that returns the object, then calling the beep() method on that returned object.

That’s why your code that stored the object returned by robotFactory() to tinCan was able to work. tinCan is assigned the object that is returned by your factory function, so it has a beep() method.

3 Likes

I like to think about this like a real factory.

Imagine a physical factory that produces robot toys that say “Beep Boop”. You’ve set everything up so that all the robots go “Beep Boop”, you just need to give them a name and model and they’ll work. So, you input the name and the model (const tinCan = robotFactory('P-500')), and then you can get the robot to say “Beep Boop”. But if you ask the factory to say “Beep Boop”, it’s not going to do that; it’s a place to make things that say Beep Boop, not a place to say Beep Boop itself.

1 Like