0

First of all, I know that with the help of this it is possible to access properties or methods within a javascript object, but something doesn't work in my example.

module.exports = {
    explanations: {
        '--help': 'show help',
        '--connection': 'list connections'
    },
    connections: {
        'a': '1',
        'b': '2',
        'c': '3'
    },
    manPageOfObject: function(object) {
         var output = '';
         var keys = Object.keys(object);
         for (var i in keys) {
              output += keys[i] + ': ' + object[keys[i]] + '\n';
         }
         return output;
   },
   manPages: {
       '--help': function() { return this.manPageOfObject(this.explanations); }
       '--connections': function() { return this.manPageOfObject(this.connections); }
   }
}

The function manPageOfObject should return a string/"man page" of an object.

Then I want to print a "man page" like:

var myModule = require('xyz.js');

var manPage = myModule.manPages['--help'];
console.log(manPage());

But something isn't working properly, I get the error this.manPageOfObject is not a function. But I'm pretty sure it is one, isn't it?

I appreciate any help. Thanks.

Habebit
  • 533
  • 3
  • 14

2 Answers2

1

You have nested objects, which means you haven't one single context.

manPageOfObject is at the myModule. So for a function to find manPageOfObject, it must have as context (as this) the myModule object.

Now, manPage is an object of its own. It doesn't have a manPageOfObject property. So if you just do manPage.something(), and something() tries to use a manPageOfObject property, it won't find it because manPage hasn't one.

You have to bind myModule.manPage['--help'] to myModule (myModule.manPage['--help'].bind(myModule)) for it to be able to pick manPageOfObject in this:

var myModule = {
  explanations: {
    '--help': 'show help',
    '--connection': 'list connections'
  },
  connections: {
    'a': '1',
    'b': '2',
    'c': '3'
  },
  manPageOfObject: function(object) {
    var output = '';
    var keys = Object.keys(object);
    for (var i in keys) {
      output += keys[i] + ': ' + object[keys[i]] + '\n';
    }
    return output;
  },
  manPage: {
    '--help': function() {
      return this.manPageOfObject(this.explanations);
    },
    '--connections': function() {
      return this.manPageOfObject(this.connections);
    }
  }
};
var manPage = myModule.manPage['--help'].bind(myModule);
console.log(manPage());
acdcjunior
  • 114,460
  • 30
  • 289
  • 276
0

What error are you getting when you try to run it? It might be a good hint.

var manPage = myModule.manPages['--help'];
                               ^
TypeError: Cannot read property '--help' of undefined

You've got a typo. You're exporting manPage not manPages. Your next problem is going to be where this comes from.

Sean
  • 1,239
  • 9
  • 16