DEV Community

Cover image for JavaScript factory functions and Object.create()
Ahmad Mukahal
Ahmad Mukahal

Posted on

5 1

JavaScript factory functions and Object.create()

Do you know JavaScript factory function and its issues, and why we use Object.create() method instead?

Hello 🖐,

Factory functions in JS are any function that return an object.

like this one:

function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName() {
            return firstName + ' ' + lastName;
        }
    }
}
const person1 = createPerson("Ahmad", "Mukahal");
const person1 = createPerson("john", "Deo");

Enter fullscreen mode Exit fullscreen mode

and so on...

With the factory function, you create any number of the person objects you want without duplicating code.

What if we have one thousand persons? It will store a thousand objects in the memory heap! and this is not an efficient way.

Example:
Each object will have a different address in the memory and every object will have the getFullName() method, Ooh no, I'm not DRY!!

This is why the Object.create() method comes into play.

The Object.create() method creates a new object using an existing object as the prototype of the new object:

const person = {
firstName : "John",
lastName: "Deo",
getFullName() {
            return firstName + ' ' + lastName;
        }
}
Enter fullscreen mode Exit fullscreen mode

// Make prototype chain:

const me = Object.create(person);
Enter fullscreen mode Exit fullscreen mode

so, now me object has all properties and methods in person object, and it can hold its own props and methods and override props and methods as you want like this:

console.log(me.firstName) // John
me.firstName = "Ahmad";
me.lastName = "Mukahal";
console.log(me.firstName) // Ahmad
Enter fullscreen mode Exit fullscreen mode

What efficient is that !!

Hopefully enjoyed reading.

Ahmad Mukahal 🌹

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay