JavaScript模块私有功能

时间:2017-08-23 00:29:03

标签: javascript

使用下面的模块,如何添加不公开的功能?这不是揭示模块。假设我不希望滚动公开?不是说这是正确的,因为roll是有用的。但是如何隐藏呢?

/* global module */

module.exports = (function () {
  'use strict';
  var random;

  function Dice(random) {
    this.init(random);
  }

  Dice.prototype.init = function (random) {
    this.random = random || Math.random
  };

  Dice.prototype.d20 = function() {
    var max = 20;
    var min = 1;
    return this.roll(min, max);
  };

  Dice.prototype.d6 = function() {
    var max = 6;
    var min = 1;
    return this.roll(min, max);
  };

  Dice.prototype.roll = function(min, max) {        
    return Math.floor(this.random() * (max - min)) + min;
  };

  return Dice;
}());

2 个答案:

答案 0 :(得分:2)

私有函数实际上不是Javascript的一部分。但你可以模仿它们。这是一个例子..



var Roller = (function () {
  
  //constructor
  function Roller(name) {
    this.name = name;
  }
  
  //public method
  Roller.prototype.callPrivate = function() {
    //just need to remember to pass this
    //to our private functions
    private_roll(this);
  }
  
  //private function
  function private_roll(that) {    
    console.log(that.name);
  }

  //lets return our class.
  return Roller;
})();

 
var roller = new Roller('Test Me!');
roller.callPrivate();

//these will fail, 
//private_roll(roller);
//roller.private_roll(roller);
//IOW: no acces to private_roll from outside
//the closure..




答案 1 :(得分:1)

如果您不需要掷骰来了解骰子,您可以使用正常的函数而不是类中的方法。

module.exports = (function () {
  function roll (min, max, random) {
    return Math.floor(random() * (max - min)) + min
  }

  function Dice (random) {
    this.init(random)
  }

  /**
   * rest of your class definition
   */

  Dice.prototype.d6 = function() {
    var max = 6
    var min = 1
    return roll(min, max, this.random)
  }
})())