Home > UI Developer > Don’t you need a constructor function to specify object instantiation behavior and handle object initialization?

Don’t you need a constructor function to specify object instantiation behavior and handle object initialization?


No.

Any function can create and return objects. When it’s not a constructor function, it’s called a factory function.

let animal = {
  animalType: 'animal',
 
  describe () {
    return `An ${this.animalType} with ${this.furColor} fur, 
      ${this.legs} legs, and a ${this.tail} tail.`;
  }
};
 
let mouseFactory = function mouseFactory () {
  return Object.assign(Object.create(animal), {
    animalType: 'mouse',
    furColor: 'brown',
    legs: 4,
    tail: 'long, skinny'
  });
};

let mickey = mouseFactory();

More : https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a

Categories: UI Developer
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment