Experimenting with a OOP design pattern in JavaScript












0















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.



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 thing of this approach to OOP in JavaScript?





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>











share



























    0















    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.



    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 thing of this approach to OOP in JavaScript?





    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>











    share

























      0












      0








      0








      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.



      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 thing of this approach to OOP in JavaScript?





      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>











      share














      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.



      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 thing of this approach to OOP in JavaScript?





      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>








      // 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>





      // 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>






      javascript object-oriented





      share












      share










      share



      share










      asked 2 mins ago









      IvanIvan

      330111




      330111






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211382%2fexperimenting-with-a-oop-design-pattern-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211382%2fexperimenting-with-a-oop-design-pattern-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'