0
Onclick assignment in js, function of object returns "undefined"
(i attached a code) basically, the title says it all. If i create an element in javascript and assign an onclick function that rerurns an object variable to it, it always returns undefined. I dont know the cause and how to fix it. Help would be appreciated https://code.sololearn.com/W8r8fJp15XA5/?ref=app
2 Respuestas
+ 2
Thats one of the many javascript quirks.
btn.onclick = obj.getv
will override the "this" variable inside the getv function. Event handlers specifically will make "this" into an event. (You can try `console.log(this.target)` inside your getv function to see it. You never defined a "target" but since "this" is something else, it's there)
to fix it, you can do:
btn.onclick = function(){ obj.getv(); }
Or
btn.onclick = () => obj.getv();
Or the more exotic, fixing the value of "this" so it can't be changed later:
btn.onclick = obj.getv.bind(obj);
0
thanks :)