rivnatmalsa
rivnatmalsa

Reputation: 650

Unable to use variable outside of class in the class

I am making a simple note taking app to learn node and ES6. I have 3 modules - App, NotesManager and Note. I am importing the Note class into the NotesManager and am trying to instantiate it in its addNote function. The problem is that even though the import is correct, it turns out to be undefined inside the class definition. A simpler solution would be to just instantiate the NotesManager class and add the Note class to its constructor however, I want to have NotesManager as a static utility class.

Here is my code. Note.js

class Note {
  constructor(title, body) {
    this.title = title;
    this.body = body;
  }
}

module.exports = Note;

NotesManager.js

const note = require("./Note");
console.log("Note: ", note); //shows correctly

class NotesManager {
  constructor() {}

  static addNote(title, body) {
    const note = new note(title, body); //Fails here as note is undefined
    NotesManager.notes.push(note); 
  }

  static getNote(title) {
    if (title) {
      console.log(`Getting Note: ${title}`);
    } else {
      console.log("Please provide a legit title");
    }
  }

  static removeNote(title) {
    if (title) {
      console.log(`Removing Note: ${title}`);
    } else {
      console.log("Please provide a legit title");
    }
  }

  static getAll() {
    //console.log("Getting all notes ", NotesManager.notes, note);
  }
}

NotesManager.notes = []; //Want notes to be a static variable

module.exports.NotesManager = NotesManager;

App.js

console.log("Starting App");
const fs = require("fs"),
  _ = require("lodash"),
  yargs = require("yargs"),
  { NotesManager } = require("./NotesManager");

console.log(NotesManager.getAll()); //works
const command = process.argv[2],
  argv = yargs.argv;
console.log(argv);
switch (command) {
  case "add":
    const title = argv.title || "No title given";
    const body = argv.body || "";
    NotesManager.addNote(title, body); //Fails here
    break;
  case "list":
    NotesManager.getAll();
    break;
  case "remove":
    NotesManager.removeNote(argv.title);
    break;
  case "read":
    NotesManager.getNote(argv.title);
    break;
  default:
    notes.getAll();
    break;
}

Is it possible for me to create a strict utility class which I can use without instantiating like in Java? Pretty new here and have tried searching for it without any luck. Thank you for your help.

Upvotes: 0

Views: 689

Answers (1)

Mark
Mark

Reputation: 92461

When you do this:

const note = new note(title, body);

you redefine note shadowing the original note from the outer scope. You need to pick a different variable name.

Something like this should work better:

static addNote(title, body) {
    const some_note = new note(title, body); //Fails here as note is undefined
    NotesManager.notes.push(some_note); 
}

Upvotes: 2

Related Questions