揭示JavaScript中的模块模式

179 阅读1分钟

你可以在JavaScript中使用揭示模块模式,使用闭包来维护私有信息,同时只暴露你需要的信息。

问题所在

让我们考虑下面这个例子,我们创建了一个对象clarkKent

const clarkKent = {
  name: 'Clark Kent',
  secretIdentity: 'Superman',
  introduce: function () {
    return `Hi, my name is ${this.name}.`;
  },
  issuesReport: function () {
    return `${this.secretIdentity} saves the day!`;
  },
};

使用这个例子,克拉克可以介绍自己,并可以报告说超人拯救了一天。

console.log(clarkKent.introduce());
// Hi, my name is Clark Kent.
console.log(clarkKent.issuesReport());
// Superman saves the day!

这很好,但是,哦,不!我们可以接触到克拉克的秘密身份!"。

console.log(clarkKent.secretIdentity);
// Superman

揭示模块模式来拯救

我们可以绕过这个问题的一个方法是使用揭示模块模式。揭示模块模式使用一个立即调用的函数表达式(IIFE)来创建封闭的变量,我们想在模块中访问这些变量,但不想暴露在工程中。

让我们看看克拉克是如何做到这一点的。

const clarkKent = (function () {
  const name = 'Clark Kent';
  const secretIdentity = 'Superman';
  const introduce = function () {
    return `Hi, my name is ${name}`;
  };
  const issuesReport = function () {
    return `${secretIdentity} saves the day!`;
  };

  return { introduce, issuesReport };
})();

console.log(clarkKent.introduce());
// Hi, my name is Clark Kent.
console.log(clarkKent.issuesReport());
// Superman saves the day!
console.log(clarkKent.secretIdentity);
// undefined

完美!"。我们在我们不想暴露的秘密信息周围创建了一个闭合,并且只暴露了我们模块中的introduceissuesReport 方法!

结论

虽然这是一个有点傻的例子,但重要的是要注意到,我们有工具和模式来维护隐私,重要的是,不要把信息暴露在真正需要的地方。