Search code examples
javascriptprototype

Accessing prototype method or function undefined


I'm learning to work with prototype but have some problems in exporting and using it in other files. The require part works but I can't access to the properties or methods in my data.js.

If i want use myFunction I'm getting myFunction is not a function and for properties undefined

I also don't understand why function(){}; instead of let Data = {}; works...

// data.js
let Data = function(){}; 

Data.prototype.integers = [0,1,3,2,8,4,11,22,74,98,111,5];

Data.prototype.myFunction= function (text){
  return text
}
module.exports.Data  = Data;


// main.js
let Numbers = require ("./data.js");
console.log(Numbers.myFunction("some text"), Numbers.integers ); // myFunction is not a function

Solution

  • It's because you're adding members to Data.prototype.

    Change module.exports.Data = Data with module.exports.Data = new Data().

    Some advise

    Unless you want to do stuff with object-oriented programming, I would refactor your code as follows:

    // data.js
    module.exports.Data = {
       integers: [0,1,3,2,8,4,11,22,74,98,111,5],
    
       myFunction: function (text){
            return text
       }
    }
    

    So you're code in main.js will work as well.