如何使用ES6访问返回对象(模块模式)中的“公共”功能?

时间:2017-01-15 23:46:45

标签: javascript design-patterns ecmascript-6 module-pattern

在ES5中使用模块模式时,调用this.methodName会在返回对象中给出methodName。但是在ES6中它现在有点不同......

旧方式(使用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 

新方式(使用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

有很多方法......

  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.

这样,更改模块的名称不应该是一个大问题:

  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.

如何使用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?
      }
    };
  })();

1 个答案:

答案 0 :(得分:0)

您可以使用对象方法的简写语法,例如getItemCount()

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

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

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

moduleES6.getTotal() //4