0

When I try to output a property to the console inside a method, I get error error1 is not defined for error1 and console message "undefined" for error2. What am I doing wrong?

class myClass {
  constructor(setting) {
    let error1 = ["fdf", "gff"];
    this.error2 = ["fdf", "gff"];

    for (let i = 0; i < formFields.length; i++) {
        if (formFields[i].tagName === "BUTTON") {
        continue;
    }
      formFields[i].addEventListener("change", this.method.bind(this);
    } 
   }
   isValid(el){
   ...
  }
  method(){
    isValid(this)
    console.log(error1); 
    console.log(this.error2);
  }

Here's a complete example on codsandbox. https://codesandbox.io/s/sleepy-moon-m9kr6?file=/src/index.js

Dio
  • 245
  • 3
  • 15
  • 1
    The problem involves how your code calls `.method()`, but that code is not in your question. – Pointy Nov 10 '21 at 12:46
  • I hang an event handler on the input in the constructor and call the method onChange event. PS added to code – Dio Nov 10 '21 at 13:25
  • 1
    Yes, and as you can see from the linked duplicate question that won't work. The `this` context is lost when you register the method as an event handler unless you take precautions to avoid that happening. – Pointy Nov 10 '21 at 13:27
  • Made this.checkIt.bind(this). I'm still very confused with this and its context. Now it works, thank you. – Dio Nov 10 '21 at 13:31
  • @Pointy only thing I still can't figure out is how to correctly call **isValid(this)** inside the **method()** method to save the **this** parameter in which I pass the input node. – Dio Nov 10 '21 at 14:01
  • You have to call `this.isValid(this)` (and you don't really need to explicitly pass `this`, because if you call it with `this.isValid()` then `this` will be correct anyway). [This old question](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) has a lot of explanations about `this` and the ways the value is controlled. – Pointy Nov 10 '21 at 14:16
  • @Pointy But if I call this.isValid(this) or this.isValid () I get the whole class, but not the input node. I have to access the current to manipulate its parameters. – Dio Nov 10 '21 at 14:27
  • @Pointy When I do like this ```addEventListener("change", this.checkIt.bind(this)``` then ```checkIt() { console.log(this); }``` it is not the node that is displayed, but my entire class MyClass is displayed. And I need to somehow get the node of the current input. – Dio Nov 10 '21 at 14:47
  • 1
    But if `this` is not a reference to your class, you won't be able to call `checkIt()`. The event object passed to the event handler should have the target element reference. – Pointy Nov 10 '21 at 16:27

0 Answers0