Ahmed Gaafer
Ahmed Gaafer

Reputation: 1661

function.prototype not working properly with module.exports

I have a file that includes the current function

function foo(){
  /*Some members*/
}

foo.prototype.func = function(p1){
  /*some logic*/
  return this
}

module.exports = foo

and in the test file

let x = require('First file path');

x.func(p1) /*Throws an error that it's not defined*/ 
x.prototype.func(p1)/* works normally */


/*I also tried*/

let obj = x();


I am trying to make an npm package and it's not practical to type the prototype every time how to solve this?

Upvotes: 0

Views: 70

Answers (1)

Dolly
Dolly

Reputation: 2592

Your foo.js should be

function foo() {
    /*Some members*/
}

foo.prototype.func = function (p1) {
    /*some logic*/
    console.log(p1);
}

module.exports = foo;

and usage file should be:

var foo = require('./foo');

var instance = new foo(); //<---notice here

console.log(instance.func("hello"));

Upvotes: 1

Related Questions