无法在课程中的课程外使用变量

时间:2018-08-03 00:38:09

标签: node.js ecmascript-6

我正在做一个简单的笔记应用程序来学习节点和ES6。我有3个模块-App,NotesManager和Note。我将Note类导入NotesManager,并尝试在其addNote函数中实例化它。问题是,即使导入正确,但在类定义中却未定义。一个更简单的解决方案是只实例化NotesManager类并将Note类添加到其构造函数中,但是,我想将NotesManager作为静态实用程序类。

这是我的代码。 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;
}

是否可以创建一个严格的实用程序类,而无需像Java中那样实例化就可以使用它?这里很新,并且尝试没有任何运气寻找它。谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

执行此操作时:

self.previewPlayer.replaceCurrentItem(with: AVPlayerItem(url: URL(fileURLWithPath: url)))
self.previewPlayer.play()

您重新定义了const note = new note(title, body); ,从外部范围中遮盖了原始note。您需要选择其他变量名称。

类似的东西应该会更好地工作:

note