How can one use this code in personal projects? what does it do exactly for you

111 views Asked by At

I've been having issues with the structure of my vanilla js code, with regards to local/global variables/methods, inheritance, etc.

my search for a good example of code found this script:markerwithlabel.js

im curious about this bit:

/**
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 * @private
 */
function inherits(childCtor, parentCtor) {
  /* @constructor */
  function tempCtor() {}
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /* @override */
  childCtor.prototype.constructor = childCtor;
}

source: https://github.com/googlemaps/v3-utility-library/blob/master/packages/markerwithlabel/src/markerwithlabel.js

How can one use this code in personal projects? what does it do exactly for you.

apparently this snippet is widely used: https://github.com/search?p=5&q=%22function+inherits%28childCtor%2C+parentCtor%29+%7B%22&type=Code

1

There are 1 answers

2
Mosia Thabo On

This is the prototypal way of performing inheritance in javascript. This function inherits(childCtor, parentCtor) simply passes properties and features from parentCtor to childCtor. It's an object oriented principle of sharing features between related objects. This code does exactly what extends in es2015 does in objects. Please refer to my comments below, I tried to be open and not more technical.

function inherits(childCtor, parentCtor) 
{
  // This declares a function to be used as a constructor for childCtor
  function tempCtor() {}
      // This copies the prototype of the parent to the temporary class which is thechild, 
      // remember that the parent's prototype has properties that the child is inheriting
      tempCtor.prototype = parentCtor.prototype;
      // this adds a property called superClass inside child object that informs it who the parent is. so when you access that property it will refer to the parent
      childCtor.superClass_ = parentCtor.prototype;
      // This is where the new instance of child object is created through using tempCtor as the basis because all data was stored in it.
      childCtor.prototype = new tempCtor();

  // this then informs the childCtor that the method called constructor refers to itself
  childCtor.prototype.constructor = childCtor;
}

I just wanted to make it quick, You can read further more on this topic here