Rellfy Rellfy - 5 months ago 13
Node.js Question

Javascript object function is returning null

I'm trying to do a very simple OOP in Javascript (Node.js) but having issues. I tried everything already, including searching, but did not find an answer.

Basically, I have this file Test.js:

class Test {

constructor(){
this.name = 'Hey';
this.config = 'null!';
console.log('this.config: ' + this.config);
}

config(msg){
this.config = msg;
console.log('new this.config: ' + this.config);
}

}

module.exports = Test;


(I also tried this:)

function Test()
{
this.name = 'Hey';
this.config = 'null!';
console.log('this.config: ' + this.config);
}

Test.config = function(msg) // and Test.prototype.config
{
this.config = msg;
console.log('new this.config: ' + this.config);
}

module.exports = Test;


And I have this other file app.js:

var TestModule = require('./Test.js');
var Test = new TestModule();
var test = Test.config('hi');


Other way I've tried:

var TestModule = require('./Test.js');
var Test = new TestModule().config('hi');


and also did not work.

I tried many different things already, but no matter what, when I try to run the config function in the same instance, the object turns null... does anyone know why that happens? Maybe I'm missing something really obvious.

Answer

You first snippet is correct

class Test {

    constructor() {
      this.name = 'Hey';
      this.config = 'null!';
      console.log('this.config: ' + this.config);
    }

    config(msg) {
      this.config = msg;
      console.log('new this.config: ' + this.config);
    }

  }

  module.exports = Test;

config is an instance method not a class method or static method.

You need to call config() on a Test instance. like

var Test = require('./Test.js');
var testObj = new Test();

Now testObj is instance and you can call config() method on this object.

test.config('Hi');

It will print/log a message but it will not return any thing but undefined because you are not returning anything from that method.

I hope this explains the problem.