Javascript 对象函数返回 null

Javascript object function is returning null

我正在尝试在 Javascript (Node.js) 中做一个非常简单的 OOP,但遇到了问题。我已经尝试了所有方法,包括搜索,但没有找到答案。

基本上,我有这个文件 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;

(我也试过这个:)

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;

我还有这个文件 app.js:

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

我试过的其他方法:

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

也没有用。

我已经尝试了很多不同的东西,但无论如何,当我尝试 运行 同一实例中的配置函数时,对象变为空...有人知道为什么会这样吗?也许我遗漏了一些非常明显的东西。

您正在将 var Test 指定为 config 函数的 return 值。

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

由于 config 没有 return 任何东西,这将导致 test 为空。

你应该让你的 config 方法 return 一些东西(这将是 "method chaining" design pattern 的一种形式),或者干脆不分配 config 的结果调用一个变量。

例如,您可以简单地这样做:

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

你的第一个片段是正确的

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 是实例方法,不是 class 方法或静态方法。

您需要在测试实例上调用 config()。喜欢

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

现在 testObj 是实例,您可以在此对象上调用 config() 方法。

test.config('Hi');

它会 print/log 一条消息,但它不会 return 除了 undefined 之外的任何东西,因为你没有 return 从该方法中获取任何东西。

我希望这能解释问题。