0

I wonder how I can pass a class property into function located in a .each of a method as below. I have found that I could call the property from the newly created instance but it means the class can't be replicated. Is there a object inheritance friendly way of calling the class property from inside a function located in function > .each > method > class?

class ok {
  constructor() {
    this.jojo = "first state";
  }

  myMethod() {
    let rp = require('request-promise-native');
    let cheerio = require('cheerio');
    rp("https://tomydna.com")
      .then(response => {

        let $ = cheerio.load(response);

        $('a').each(function() {
          this.jojo = "second state"; // This does not work
          ok1.jojo = "second state from outside"; // This would work but it is not good because it is related to one instance only. If a new Instance is created the method stops working.
          console.log(ok1.jojo); // will replicate as many times it finds url on the page.
        });


      });

  }

}

ok1 = new ok();
ok1.myMethod();
Nicolas Guérinet
  • 2,086
  • 1
  • 29
  • 38

3 Answers3

2

You can assign this object into another variable. You can not use class ok this object into .each function because inside .each this represent current immediate object(.each function callback), following example may help you

class ok {

    constructor() {
        this.jojo = "first state";
    }

    myMethod() {
        let self = this;
        let rp = require('request-promise-native');
        let cheerio = require('cheerio');
        rp("https://tomydna.com")
            .then(response => {

                let $ = cheerio.load(response);

                $('a').each(function () {
                    self.jojo = "second state"; // This will work
                    ok1.jojo = "second state from outside"; // This would work but it is not good because it is related to one instance only. If a new Instance is created the method stops working.
                    console.log(ok1.jojo); // will replicate as many times it finds url on the page.
                });


            });

    }

}

ok1 = new ok();
ok1.myMethod();
Arif Khan
  • 5,039
  • 2
  • 16
  • 27
0

In your .each callback, you can use an arrow function. Be sure though if you want to have a reference to the cheerio dom node that your callback is of the form (index, node) => {/* your code */}.

adz5A
  • 2,012
  • 9
  • 10
0

its just a scope issue. Assign this to a local variable and then use it inside your each. eg:

  myMethod() {
    let that = this; //local variable
    let rp = require('request-promise-native');
    let cheerio = require('cheerio');
    rp("https://tomydna.com")
      .then(response => {

        let $ = cheerio.load(response);

        $('a').each(function() {
          that.jojo = "second state"; // usage
          console.log(that.jojo); 
        });


      });

  }
mirg
  • 312
  • 2
  • 16