Home > Blockchain >  hold an private array with module pattern js
hold an private array with module pattern js

Time:05-07

I'm using module pattern on JS. Trying to make 2 private properties which first property will hold the number i.e 3. The second property is array of string which hold the items. I've been trying but it gives me an error (undefined)

//MODULE DESIGN PATTERN
var myModule = function() {
  //PRIVATE PROPERTIES AND METHODS
  var holdNumber = 3;
  var arrhold = [];

  //private
  function PrivateMessage(obj) {
    console.log("Object successfully added: "   obj)
  }

  //public
  function addObject(obj) {
    arrhold.push(obj);
    PrivateMessage(obj);
  }

  return {
    addItem: addObject
  }
}();

console.log(myModule.addItem("A"));
console.log(myModule.addItem("A"));

CodePudding user response:

addObject does not return any data from arrhold. If you want to add and print that array, you should add return to addObject

//MODULE DESIGN PATTERN
var myModule = function() {
  //PRIVATE PROPERTIES AND METHODS
  var holdNumber = 3;
  var arrhold = [];

  //private
  function PrivateMessage(obj) {
    console.log("Object successfully added: "   obj)
  }

  //public
  function addObject(obj) {
    arrhold.push(obj);
    PrivateMessage(obj);
    return arrhold; //return arrhold
  }

  return {
    addItem: addObject
  }
}();

console.log(myModule.addItem("A"));
console.log(myModule.addItem("A"));

CodePudding user response:

addObject doesn't return anything, so the console.log(myModule.addItem("A")) is undefined

You can return arrhold which will give you the desired value:

//MODULE DESIGN PATTERN
var myModule = function() {
  //PRIVATE PROPERTIES AND METHODS
  var holdNumber = 3;
  var arrhold = [];

  //private
  function PrivateMessage(obj) {
    console.log("Object successfully added: "   obj)
  }

  //public
  function addObject(obj) {
    arrhold.push(obj);
    PrivateMessage(obj);
    return arrhold
  }

  return {
    addItem: addObject
  }
}();

console.log(myModule.addItem("A"));
console.log(myModule.addItem("A"));

  • Related