-2
I’m trying to move my application to the paradigm OO, but at the time of picking the value of the input is returned Undefined.
I wanted to know the why that this error is made, and the addeventlistener keeps working and how I could solve.
class Test {
constructor() {
this.test1 = document.getElementById("test");
}
method(e) {
let varTest1 = this.test1.value;
console.log(varTest1);
}
methodRun(e) {
this.test1.addEventListener("change", this.method);
}
}
let run = new Test();
run.methodRun();
<html>
<body>
<input type="number" id="test">
</body>
</html>
pardon for naivety, but I didn’t quite understand it yet, mainly the part of var _self = this and the part of sending the part that is "Function" of the method.
– João Vítor
@Joker the Function() {} has a separate scope, this is not a variable, so to pass to another scope you have to set in a var. Or use Arrow Function() => which treats everything in the same scope.
– Guilherme Nascimento
Can you tell me if there’s another way to solve this problem? I’m still a little confused here.
– João Vítor
@Joker is exactly what I presented in the answer, to pass the method needs to pass the instantiated object, you are using OO in a JS code, this is how it resolves, passing to the other context... another way to solve is not to use OO without need, in fact most of the use of OO is unnecessary, someone invented that OO was magic solution to everything, which is not true. What I recommend is that you learn what scope is, so it will be more obvious where you need to improve.
– Guilherme Nascimento
@Joker read Reference loss in function call and What is the difference between Function() {} and () => {}?
– Rafael Tavares