【问题标题】:NodeJS TypeError: Cannot read property of undefinedNodeJS TypeError:无法读取未定义的属性
【发布时间】:2017-03-06 07:24:06
【问题描述】:

所以我刚开始使用 NodeJs 还有很多东西要学,但到目前为止我很喜欢它,我遇到了这个问题,我找到了答案,但这不是我想要的,这有点奇怪,让我展示一些代码并解释一下

p>

所以我有 2 个文件

文件 1 > app.js(主)

文件 2 > UserEntity.js(模块)

app.js:

var uEntity = require('./UserEntity.js');

var hm = new uEntity.person();
console.log(hm.info.strUsername);

UserEntity.js:

function User() {
    this.info = {
        'strUsername': 'Hashimoro'
    };
}

module.exports.person = User;

我正在创建一个新的 UserEntity 我想直接访问信息,正如您从代码中看到的那样

但它给出了这个错误:

console.log(hm.info.strUsername);
                   ^

TypeError: Cannot read property 'strUsername' of undefined
    at Object.<anonymous> (D:\NodeLearn\Testing\app.js:4:20)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

如果有人能给出修复和解释会很棒

谢谢,非常感谢

【问题讨论】:

  • 您使用的节点版本是什么?这对我有用,我有预期的结果。
  • 所以你有一个名为 app.js 的文件和另一个名为 App.js 的文件?
  • 我使用的是最新的 LTS 6.9.1,不,我只有一个 app.js
  • 也适合我。没有什么问题是看不出来的。
  • sayHello() 有效,我正在尝试直接访问它 2 个答案已经给出并得到了很好的解释:)

标签: javascript node.js


【解决方案1】:

也从函数返回info 对象。

    function User() {
        this.info = {
            'strUsername': 'Hashimoro'
        };

        return {
            sayHello: ()=> { console.log('Username is: ' + info.strUsername); }
,
info : this.info
        };
    }

    module.exports.person = User;

【讨论】:

  • 哦,哇,完美不知道您必须退货,现在我知道了,非常感谢您:),所以通过退货,您可以通过要求访问它吗?
【解决方案2】:

这看起来与 Node 模块的典型编写方式略有不同。

有很多关于如何编写它们的资源here

你可以重构成这样:

UserEntity.js:

function User() {
  this.info = {
    'strUsername': 'Hashimoro'
  };
}

User.prototype.getInfo = function() {
  return this.info;
};

module.exports = User;

app.js

var Person = require('./UserEntity.js');
var person = new Person();

console.log(person.info.strUsername);

// OR
console.log(person.getInfo().strUsername);

【讨论】:

    【解决方案3】:

    使用 es6 类应该是这样的。更明确地说明您导出的对象:

    app.js

    var uEntity = require('./UserEntity.js');
    
    var hm = new uEntity.person();
    console.log(hm.info.strUsername);
    hm.sayHello();
    

    UserEntity.js

    'use strict';
    
    class User {
      constructor() {
        this.info = {
          'strUsername': 'Hashimoro'
        };
      }
    
      sayHello () { 
        console.log(`Username is: ${this.info.strUsername}`);
      }
    }
    
    module.exports = {
      person: User
    };
    

    【讨论】:

      【解决方案4】:

      就我而言,我没有添加这个 JSON 中间件

      app.use(express.json());
      

      【讨论】:

        猜你喜欢
        • 2022-09-23
        • 2022-11-29
        • 2017-08-30
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2018-06-02
        • 2020-03-25
        相关资源
        最近更新 更多