Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this possible to design a function which takes a parameter and returns an object which holds multiple properties or functions

For example:

var resultList = [];
var objectName = (userName) => {

};

objectName.rowCount; // return overall count
objectName.fetchNext(); // updated data will be available in resultList

I have tried multiple solutions with no result like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var resultList = [];
var objectName = (userName) => {
  var rowCount = 0;
  init() {
    // make call to server and read data
    rowCount = 5; // setting dummy data
  };

  fetchNext = function(){
       // logic here
       resultList = [] // new data
  };

  
  init();
};

EDIT

Another attempt

var x = function(){
    var a = function(){console.log('a');};
    var b = function(){console.log('b');};
    return {a: a, b: b};
}
x.a(); // not able to call this function

>Solution :

You can’t use an arrow function as a constructor, so tyou could change your code to use a traditional function:

function objectName(userName)  {
  var rowCount = 0;
  init = function() {
    // make call to server and read data
    rowCount = 5; // setting dummy data
  };

  this.fetchNext = function(){
       // logic here
       const resultList = [] // new data
       return resultList;
  };

  
  init();
};

var myObj = new objectName("foo");
console.log(myObj.fetchNext());

Or, you can return an object from your arrow function

var objectName = (userName) => {
  var rowCount = 0;
  function init() {
    // make call to server and read data
    rowCount = 5; // setting dummy data
  };

  
  
  init();
  
  return {
    fetchNext: function(){
       // logic here
       const resultList = [] // new data
       return resultList;
    }

  }
};

var myObj = objectName("Foo");
console.log(myObj.fetchNext());

Related:


For completeness, the reason your edit did not work is that you defined x but never executed the function. This works:

var x = function(){
    var a = function(){console.log('a');};
    var b = function(){console.log('b');};
    return {a: a, b: b};
}
x().a(); // must execute x to get the result

And is esssentially the same as my second example above

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading