FranXh
FranXh

Reputation: 4771

JavaScript and NodeJS: Calling method from different JS file

I am using NodeJS to include one js file into another. Below I show both my files. Both classes contain constructor for two objects. I would like to call a method in ClassB from ClassA. In ClassA, I require ClassB (as shown below) and I am trying to create a new instance of class B, and calling on it the method get of class B. I get the following error:

cB.get();
   ^
TypeError: Cannot call method 'get' of undefined
    at Object.<anonymous> (/home/---/ClassA.js:12:4)

//ClassA.js

var imported = require('./ClassB');

function ClassA() 
{
    //....
}

var cA = new ClassA();
var cB = imported.ClassB();

cB.get();

//ClassB.js

function ClassB() 
{

    var myVar = 'test';

    function _get ()
    {
        return myVar;
    };

    this.get = function ()
    {
        return _get();
    };
 }

 exports.ClassB = ClassB;

I believe the problem is at how I instantiate the object of class B. Is there a way around this?

Upvotes: 1

Views: 213

Answers (3)

Jackie
Jackie

Reputation: 23519

Here is my answer

ClassA

var ClassB = require('./ClassB');
var cB = new ClassB("Test");
console.log(cB.get());

ClassB:

function ClassB(myVar){
  this.myvar = myVar;
};
ClassB.prototype.get = function(){
  return this.myvar;
};
module.exports = ClassB;

CMD

$ node ClassA.js 
Test

ClassBV2

function ClassB(){
  this.myvar = "Test";
};

If you need _get to be private

function ClassB(){
  this.myvar = "Test";
};
ClassB.prototype.get = function(){
  return _get();
};
_get = function(){
  return "Other";
}
module.exports = ClassB;

If you try to use it....

console.log(cB._get());
           ^
TypeError: Object #<ClassB> has no method '_get'

Upvotes: 1

Brian Noah
Brian Noah

Reputation: 2972

You need to instantiate a constructor

function ClassB() 
{

    var myVar = 'test';

    function _get ()
    {
        return myVar;
    };

    this.get = function ()
    {
        return _get();
    };
 }

 exports.ClassB = new ClassB();

Upvotes: 1

SLaks
SLaks

Reputation: 887375

You forgot the new keyword when creating the instance.

Upvotes: 1

Related Questions