+ 3

how to write a function passed as an argument in a constructor?

Hello Javascript Expert. Here is my problem. In my code, a constructor makes buttons. Each button have its own function. How to write paramaters inside object constructor (meaning how to assign onclick attribute) correctly ? for exemple, function 'moveleft' must be assigned to 'buttonLeft' // my button constructor: function buttonConstructor(param1,param2...,action){ this.param1=param1; ... this.action=action; this.commandCreate = function(){ var btn = document.createElement("button"); ... btn.setAttribute("onclick", action); //action is assigned to the onclick attribute }; // button creation buttonLeft = new buttonConstructor("param1",...,movleft); //how i should write moveleft function assigned to action?) // function being assigned to 'action' argument function moveleft() { myCar.speedX -= 1; } regards

20th Nov 2018, 8:26 PM
Gaël Des Iris
Gaël Des Iris - avatar
4 Respuestas
+ 1
Thank you Geoffrey ! But it doesn't work on my side. I think i made something wrong. Can you explain me why using window here btn.setAttribute("onclick", window[action]()); Merci !
20th Nov 2018, 11:50 PM
Gaël Des Iris
Gaël Des Iris - avatar
+ 1
window[ "functName" ]() is a synthax to trig a function by its name without using the ugly and famous "eval()". Are you in a web environment using that code ? Or are you using javascript in another domain ? Cause "window" superglobal is only available in web.
21st Nov 2018, 6:25 AM
Geoffrey L
Geoffrey L - avatar
+ 1
If you set the 'onclick' attribute of an html element, you must assign to it a string value with the code to execute, not a function. Anyway, the good way to set an event handler at runtime is to assign a function to the element through its .addEventListener() method. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
21st Nov 2018, 2:21 PM
visph
visph - avatar
0
I took your example and here is my proposal. https://code.sololearn.com/WzurseS15TQM/#js
20th Nov 2018, 8:55 PM
Geoffrey L
Geoffrey L - avatar