Onclick assignment in js, function of object returns "undefined" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

12th Sep 2017, 2:42 PM
Cook1ee
2 Answers
+ 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);
12th Sep 2017, 2:57 PM
Schindlabua
Schindlabua - avatar
0
thanks :)
12th Sep 2017, 3:04 PM
Cook1ee