简体   繁体   中英

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.

You are assigning your var Test to be the return value of the config function.

var test = Test.config('hi!');

As config does not return anything, this will result in test being null.

You should either make your config method return something (this would be a form of the "method chaining" design pattern ), or simply not assign the result of the config call to a variable.

For example, you could simply do this:

var test = new TestModule();
test.config('hi!');
// the 'test' variable still contains a reference to your test module

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM