dimanche 15 janvier 2017

How to accesss a "public" function in the return object (module pattern) with ES6?

When using the module pattern in ES5, calling this.methodName gives me the methodName in the return object. But in ES6 it's a little bit different now....

The old way (with ES5):

  var moduleOld = (function() {
    //private
    var privateArray = [1,2,3,4];

    return {
      getItemCount: function() {
        return privateArray.length;
      },

      getTotal: function() {
        return this.getItemCount();
      }
    };
  })();

  //output
  console.log(moduleOld.getTotal()); //4 <-- Now, I want the same results with ES6 syntax 

The new way (with ES6):

  let moduleES6 = (()=> {
    //private
    let privateArray = [1,2,3,4];

    return {
      getItemCount: ()=> {
        return privateArray.length;
      },

      getTotal: ()=> {
        return this.getItemCount();
      }
    };
  })();

  //output
  console.log("es6 ", moduleES6.getTotal()); //Uncaught TypeError: this.getItemCount is not a function

There are ways around it...

  let moduleES6_2 = (()=> {
    //private
    let privateArray = [1,2,3,4];

    return {
      getItemCount: ()=> {
        return privateArray.length;
      },

      getTotal: ()=> {
        return moduleES6_2.getItemCount(); // I changed "this" to the module name, i.e. moduleES6_2
      }
    };
  })();

  //output
  console.log("es6 calling by module name: ", moduleES6_2.getTotal()); //works! But what if I change the module's name? Then I have to also change the function call in the getTotal function.

This way, changing the module's name shouldn't be much of an issue:

  let moduleES6_3 = (()=> {
    //private
    let privateArray = [1,2,3,4];
    function getItemCount() {
      return privateArray.length;
    }
    return {
      //getItemCount: getItemCount,
      getTotal: ()=> {
        return getItemCount(); // I am calling the private method. Not the public method!
      }
    };
  })();

  //output
  console.log("es6 by private method: ", moduleES6_3.getTotal()); //works! But I don't really use the method in the return object, but rather the private declared method.

How do I accesss a "public" function in the return object (module pattern) with ES6?

  let moduleES6 = (()=> {
    //private
    let privateArray = [1,2,3,4];
    function getItemCount() {
      return privateArray.length;
    }
    return {
      getItemCount: ()=> {
        return privateArray.length;
      },
      getTotal: ()=> {
        return this.getItemCount();//<-- how to access the public getItemCount method?
      }
    };
  })();

Aucun commentaire:

Enregistrer un commentaire