1

The very simple module that I've created to test the viability of this endeavor. Here is the beginning of SPServerApp.ts:

class SPServerApp {
    public AllUsersDict: any;
    public AllRoomsDict: any;
    constructor () {
        this.AllUsersDict = {};
        this.AllRoomsDict = {};
    }
}
module.exports = SPServerApp();

Then in my app, I have this require statement:

var serverapp = require('./SPServerApp');

I then try to access one of the dictionaries like so:

serverapp.AllUsersDict.hasOwnProperty(nickname)

But get the error:

TypeError: Cannot read property 'hasOwnProperty' of undefined

Can anybody see what I am doing wrong here?

Thanks, E.

3
  • You aren't instantiating the class. Add 'new' or create a new instance where you're requiring it. Commented Aug 14, 2016 at 1:53
  • 1
    That worked indeed. Thank you Phix. Commented Aug 14, 2016 at 13:30
  • 1
    I think this link will help you. stackoverflow.com/questions/23739044/… Commented Aug 15, 2016 at 5:23

1 Answer 1

1

The problem is that you forgot the 'new' keyword when calling the constructor. The line should read:

module.exports = new SPServerApp();

If you don't use new your constructor will be treated as a normal function and will just return undefined (since you did not return anything explicitly). Also 'this' will not point to what you expect within the constructor.

Omitting new in Node is actually quite common. But for this to work you have to explicitly guard against new-less calls in the constructor like so:

constructor () {
    if (! (this instanceof SPServerApp)) {
        return new SPServerApp();
    }
    this.AllUsersDict = {};
    this.AllRoomsDict = {};
}

BTW, in TypeScript you can also use module syntax. The TS compiler will translate this into the export/require statements. With ES6 style modules your example would look like this:

export class SPServerApp {
    public AllUsersDict: any;
    public AllRoomsDict: any;
    constructor () {
        this.AllUsersDict = {};
        this.AllRoomsDict = {};
    }
}
export var serverapp = new SPServerApp();

In your other TS file you just import:

import { serverapp } from './SPServerApp';

serverapp.AllUsersDict.hasOwnProperty('something');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.