NodeJS использует класс из другого файла

1

У меня есть файл сценария java, который ссылается на другой файл javascript, содержащий класс, используя

const Champion = require("./championgg_webscraper_cheerio.js");

Затем я пытаюсь создать экземпляр объекта класса Champion by

var temp = new Champion("hello");
console.log(temp);

И когда я делаю это, это выводится на консоль с указанием и неопределенной переменной:

Champion {}

Также, когда я пытаюсь распечатать свойства класса, я получаю undefined, я думаю, что у него может не быть доступа к переменной most_frequent_completed_build.

console.log(temp.most_frequent_completed_build);

Вот посмотрите файл championgg_webscraper_cheerio.js

function Champion(champName) {
  //CHEERIO webscraping
  var cheerio = require('cheerio');
  //REQUEST http library
  var request = require('request');
  //url of the champion
  var url = "http://champion.gg/champion/Camille/Top?";
  var most_frequent_completed_build;
  var highest_win_percentage_completed_build;
  request(url,
    function(error, response, html) {
      if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        var final_build_items = $(".build-wrapper a");
        var mfcb = [];
        var hwpcb = [];
        for (i = 0; i < 6; i++) {
          var temp = final_build_items.get(i);
          temp = temp.attribs.href;
          //slices <'http://leagueoflegends.wikia.com/wiki/> off the href
          temp = temp.slice(38);
          mfcb.push(temp);
        }
        for (i = 6; i < 12; i++) {
          var temp = final_build_items.get(i);
          temp = temp.attribs.href;
          //slices <'http://leagueoflegends.wikia.com/wiki/> off the href
          temp = temp.slice(38);
          hwpcb.push(temp);
        }
        most_frequent_completed_build = mfcb;
        highest_win_percentage_completed_build = hwpcb;
      } else {
        console.log("Response Error: " + response.statusCode);
      }
    }
  );
};
module.exports = Champion;
  • 0
    Можете ли вы попробовать const Champion = require("./championgg_webscraper_cheerio.js").Champion; ?
  • 0
    Я изменил объявление чемпиона: const Champion = require("./championgg_webscraper_cheerio.js").Champion; Теперь он говорит, что Champion не является конструктором, когда я пытаюсь: var temp = new Champion("hello");
Теги:
class
module
oop

3 ответа

0

Я думаю, что вам нужен конструктор Function Champion (прототип или сине-печатные классы на других языках программирования, таких как Java).

В качестве альтернативы я предлагаю вам изучить ES6 способ написания классов, который аналогичен Java.

Вы можете достичь этого, добавив все переменные или методы в эту переменную внутри конструктора функций, чтобы вы могли получить к ним доступ, используя объект, созданный с использованием ключевого слова 'new', т.е. сделайте их членами класса или методами.

В твоем случае,

function Champion(champName) {
    //Some code

    this.most_frequent_completed_build = NULL;

    //Rest of code
}

module.exports = Champion;

Просто убедитесь, что всякий раз, когда вы пытаетесь получить доступ к переменным класса, всегда используйте this.variable_name например this.most_frequent_completed_build.

Поэтому, когда вы создаете новый объект этого класса в главном приложении, вы сможете получить доступ ко всем членам класса и методам.

const Champion = require("./championgg_webscraper_cheerio.js");

var temp = new Champion("hello");
console.log(temp.most_frequent_completed_build);
0
    function Champion(champName) {
  //CHEERIO webscraping
  var cheerio = require('cheerio');
  //REQUEST http library
  var request = require('request');
  //url of the champion
  var url = "http://champion.gg/champion/Camille/Top?";
  var most_frequent_completed_build;
  var highest_win_percentage_completed_build;
  request(url,
    function(error, response, html) {
      if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html);
        var final_build_items = $(".build-wrapper a");
        var mfcb = [];
        var hwpcb = [];
        for (i = 0; i < 6; i++) {
          var temp = final_build_items.get(i);
          temp = temp.attribs.href;
          //slices <'http://leagueoflegends.wikia.com/wiki/> off the href
          temp = temp.slice(38);
          mfcb.push(temp);
        }
        for (i = 6; i < 12; i++) {
          var temp = final_build_items.get(i);
          temp = temp.attribs.href;
          //slices <'http://leagueoflegends.wikia.com/wiki/> off the href
          temp = temp.slice(38);
          hwpcb.push(temp);
        }
        most_frequent_completed_build = mfcb;
        highest_win_percentage_completed_build = hwpcb;
      } else {
        console.log("Response Error: " + response.statusCode);
      }
    }
  );
  return {most_frequent_completed_build:most_frequent_completed_build};
};
module.exports = Champion;

    var temp = new Champion("hello");
console.log(temp.most_frequent_completed_build);
0

Вы экспортируете функцию

Все, что вам нужно сделать, это вызвать такую функцию, как

var temp = Champion();

Вы можете узнать больше о new ключевом слове здесь и здесь.

  • 0
    Я изменил объявление temp как var temp = Champion("hello"); и я встречался с Cannot read property most_frequent_completed_build of undefined
  • 0
    Да. Это не так, так как область применения most_frequent_completed_build находится внутри этой функции. Вы можете вернуть это значение из функции, если вам это нужно.
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню