0
\$\begingroup\$

Initially, I was using the class syntax to structure my code. While it sure did feel nice to work with, I found it lacked some important functionalities, like private properties and interfaces. Things that I had found useful in other OOP languages like Java.

I understand JavaScript doesn't have classes, I'm trying here to experiment with prototypes. So this thread belongs more to Prototypal Class Design (no documentation there...).

I'm going for a Factory Function design, here are some of the advantages of using such technique to construct a "class" in JavaScript:

  • the factory and its instances can enclose private variables. This solves the problem of not having actual private instance/static properties usually seen in OOP languages.

  • we have control over the object's prototype allowing us to combine prototypes from different factories. This makes it possible to "extend" factories with more properties/methods or mix multiple prototypes together similar to how interfaces work in OOP languages.

  • we can keep a good structure for our factories, if we extend a factory with some methods, the instances coming from this new extended factory will remain as an instance of the initial factory. In other words, the opertator instanceof will still work.


I have implemented such design using a IIFE wrapping the actual factory function. Here's the initial factory called Person, and below a factory called Singer which extends Person's factory.

const Person = (function() {

  // private shared variables
  let total = 0;
  let average = 0;
  const updateAverage = function() {
    average = total / Person.count;
  }

  // public static attributes
  Person.count = 0;
  Person.prototype = {
    sayHi() {
      return `Hi, I'm ${this.name}`;
    }
  }

  function Person(name, age) {

    // private instance variables       

    // public instance attributes
    const properties = {
      name,
      gapToAverage() {
        return Math.abs(age - average);
      }
    }

    // some logic
    Person.count += 1;
    total += age;
    updateAverage();

    // return the instance
    return Object.create(
      Object.create(Person.prototype),              // Person's prototype
      Object.getOwnPropertyDescriptors(properties)  // Person's own public instance properties
    );

  }

  // return the constructor
  return Person;

})();
const Singer = (function() {

  let songs = {};

  const prototypeExtension = {
    sing(song) {
      return songs[song];
    }
  }

  // extend Person's prototype
  Singer.prototype = Object.create(
    Person.prototype,
    Object.getOwnPropertyDescriptors(prototypeExtension)
  );

  function Singer(name, age, songs) {

    const properties = {
      getSongTitles() {
        return Object.keys(songs);
      }
    }

    // return the instance
    return Object.assign(
      Object.create(Singer.prototype),  // Singer's prototype
      Person(name, age),                // Person's public instance properties
      properties                        // Singer's own public instance properties
    );

  }

  // return the constructor
  return Singer;

})();

This is considered the best approach to object-oriented programming in JavaScript. What do you think of this approach to OOP in JavaScript?

I know it's possible to do the exact same thing with the class syntax by declaring variables and enclosing them inside the scope of the class' constructor. Which is better though?


Here is the full code with an example:

// creating an instance of Person
const person = Person('Nina', 32);

console.log(Object.keys(person));
console.log("person instanceof Person: ", person instanceof Person)


// creating an instance of Singer
const singer = Singer('John', 20, {
  'Little Bird Fly': 'blah'
});

console.log(Object.keys(singer));
console.log("singer instanceof Person: ", singer instanceof Person)
console.log("singer instanceof Singer: ", singer instanceof Singer)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script>const Person=(function(){let total=0;let average=0;const updateAverage=function(){average=total/Person.count}
Person.count=0;Person.prototype={sayHi(){return `Hi, I'm ${this.name}`}}
function Person(name,age){const properties={name,gapToAverage(){return Math.abs(age-average)}}
Person.count+=1;total+=age;updateAverage();return Object.create(Object.create(Person.prototype),Object.getOwnPropertyDescriptors(properties))}
return Person})();const Singer=(function(){let songs={};const prototypeExtension={sing(song){return songs[song]}}
Singer.prototype=Object.create(Person.prototype,Object.getOwnPropertyDescriptors(prototypeExtension));function Singer(name,age,songs){const properties={getSongTitles(){return Object.keys(songs)}}
return Object.assign(Object.create(Singer.prototype),Person(name,age),properties)}
return Singer})()</script>

\$\endgroup\$
  • \$\begingroup\$ It doesn't look as though your sing method will function properly. Nothing updates the in-scope version of songs that it uses. But it also likely doesn't make sense here, since if that was updated, then you might get Kanye West singing Elton John's or Marian Anderson's songs... and we don't want to hear that. \$\endgroup\$ – Scott Sauyet Feb 12 at 22:23
  • \$\begingroup\$ "I know it's possible [to use the built-in syntax]... Which is better?" Although I'm not a fan of the class syntax, if it's available to you and does what you want without any additional overhead, I can't see a reason not to use it. \$\endgroup\$ – Scott Sauyet Feb 12 at 22:25
0
\$\begingroup\$

Your code looks fine except for the fact it's not super-readable. You may consider other solutions. If you look for private properties, some recommend using ES6 Symbols or WeakMaps. Babel also offers some solutions. For interfaces you can check the es6-interface npm package or naive interface implementation using Symbols. I don't know which approach is better, but one of the most important things in OOP for me is readability.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.