Medallyonify Medallyonify - 1 year ago 42
Node.js Question

Creating a function inside a function inside a class

Let's say I have some class with some function inside:

var someClass = class someClass() {
constructor() {}

function anotherFunction() {
return JSON.stringify(someObj, null, 2);

return someObj;

In this context, I could call
, and it would return
[object Object]
. Upon trying to call
, it comes up with a
TypeError: someClass.someFunction(...).anotherFunction is not a function

How could I circumvent this? I tried creating a prototype like
someClass.prototype.someFunction.anotherFunction = function() {...}
, but that doesn't work.

Many Thanks in advance,

Answer Source

You're creating a function (anotherFunction) and never doing anything with it. The JavaScript engine probably optimizes it away entirely.

If you want it to be accessible outside someFunction, you need to do something to make it accessible outside someFunction. You might return it. Or return an object that has it as a property. Or add it as a property to someObj (though that would be unusual).

So for instance, here we return a new object with both the function and the original someObj on it (because you were returning that for some reason):

var someClass = class someClass {
  constructor() {}

  someFunction(someObj) {
    function anotherFunction() {
      return JSON.stringify(someObj, null, 2);

    return {
      someObj, anotherFunction

var sc = new someClass();
var o = sc.someFunction({
  foo: "bar"

Side notes:

  • Your someClass declaration is incorrect; you shouldn't have () after in var someClass = class someClass() {.

  • The var someClass = part of that is pointless if the variable name and class name are the same. If they're different, at least use let so the hoisting is the same for the variable as it would be for the class (e.g., it's only half-hoisted).

  • The overwhelming convention in JavaScript is for constructor functions to start with a capital letter; so SomeClass, not someClass. While you can use any convention in your own code you like, I would strongly recommend using this one, it helps people reading your code. At the very least, follow it when asking questions.