Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS TypeError: Cannot read property of undefined

so I just started using NodeJs still have a lot to learn but am loving it so far I ran into this problem I found an answer, but it's not what I want it's kinda weird, let me show some code and explain

So I got 2 files

File 1 > app.js (Main)

File 2 > UserEntity.js (Module)

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;

I am creating a new UserEntity I want to access the info directly as you can see from the code

But it gives this error:

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

If someone can give a fix and explain would be great

Thank you, seriously appreciate it

like image 787
Wexo Avatar asked Oct 24 '16 13:10

Wexo


2 Answers

This looks a little different from how Node modules are typically written.

There's a great resource on how to write them here.

You can refactor to something like this:

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);
like image 94
User 1058612 Avatar answered Sep 28 '22 09:09

User 1058612


Using something es6 classes it should be like that. Be a bit more explicit about the objects that you export:

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
};
like image 34
Stavros Zavrakas Avatar answered Sep 28 '22 10:09

Stavros Zavrakas