Factory Functions vs Constructor Functions vs Class

source: https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e

// Class
class ClassCar {
  drive () {
    console.log('Vroom!');
  }
}

const car1 = new ClassCar();
console.log(car1.drive());


// Constructor
function ConstructorCar () {}

ConstructorCar.prototype.drive = function () {
  console.log('Vroom!');
};

const car2 = new ConstructorCar();
console.log(car2.drive());


// Factory
const proto = {
  drive () {
    console.log('Vroom!');
  }
};

function factoryCar () {
  return Object.create(proto);
}

const car3 = factoryCar();
console.log(car3.drive());

Each of these strategies stores methods on a shared prototype, and optionally supports private data via constructor function closures. In other words, they have mostly the same features, and could mostly be used interchangeably.

In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.

ES6 classes de-sugar to constructor functions, so everything that follows about constructor functions also applies to ES6 classes:

class Foo {}
console.log(typeof Foo); // function

Examples from Lambda School Assignments:

// Constructor

function User (options) {
    this.email = options.email;
    this.password = options.password;
    this.comparePasswords = function(x) {
        return this.password === x;
    };
};
// class.js

// Create a class called User.
// The constructor of the class should have a parameter called `options`.
// `options` will be an object that will have the properties `email` and `password`.
// Set the `email` and `password` properties on the class.
// Add a method called `comparePasswords`.  `comparePasswords` should have a parameter
// for a potential password that will be compared to the `password` property.
// Return true if the potential password matches the `password` property.  Otherwise return false.
class User {
  constructor(options) {
    this.email = options.email;
    this.password = options.password;
  }
  comparePasswords(x) {
    return this.password === x;
  }
}

const me = new User({ email: '[email protected]', password: 'p4$sw0rd' });
me.comparePasswords('passwerd'); // false

// Create a class called `Animal` and a class called `Cat`.
// `Cat` should extend the `Animal` class.
// Animal and Cat should both have a parameter called `options` in their constructors.
// Animal should have the property `age` that's set in the constructor and the method
// `growOlder` that returns the age.
// Cat should have the property `name` that is set in the constructor and the method
// `meow` that should return the string `<name> meowed!` where `<name>` is the `name`
// property set on the Cat instance.

class Animal {
  constructor(options) {
    this.age = options.age;
  }
  growOlder() {
    return (this.age += 1);
  }
}

class Cat extends Animal {
  constructor(options) {
    super(options);
    this.name = options.name;
  }
  meow() {
    return `${this.name} meowed!`;
  }
}

const jeff = new Cat({ age: 5, name: 'Jeff' });
console.log(jeff.growOlder());
console.log(jeff.meow());
// this.js

// Follow the instructions and fill in the blank sections.
// There are no tests for this file.
// To verify your code works you can run this file using `node this.js` while in the `/src` folder

class User {
    constructor(options) {
        // set a username and password property on the user object that is created
        this.username = options.username;
        this.password = options.password;
    }
    // create a method on the User class called `checkPassword`
    // this method should take in a string and compare it to the object's password property
    // return `true` if they match, otherwise return `false`
    checkPassword(str) {
        return this.password === str;
    }
}

const me = new User({
    username: 'LambdaSchool',
    password: 'correcthorsebatterystaple'
});
const result = me.checkPassword('correcthorsebatterystaple'); // should return `true`

const checkPassword = function comparePasswords(passwordToCompare) {
    // recreate the `checkPassword` method that you made on the `User` class
    // use `this` to access the object's `password` property.
    // do not modify this function's parameters
    // note that we use the `function` keyword and not `=>`
    return this.password === passwordToCompare;
};

// invoke `checkPassword` on `me` by explicitly setting the `this` context
// use .call, .apply, and .bind

// .call
checkPassword.call(me, 'correcthorsebatterystaple');
// .apply
checkPassword.apply(me, ['correcthorsebatterystaple']);
// .bind
const x = checkPassword.bind(me);
x('correcthorsebatterystaple');

results matching ""

    No results matching ""