I have a button
var startButton = $('#startButton').get(0);
that I attach the vanilla javascript onclick method to the button and call start on click.
startButton.onclick = start;
I want to use a function expression but (due to hoisting?) this doesn't call start
var start = function() {
console.log('requesting local stream');
startButton.disabled = true;
getUserMedia(constraints, gotStreamSuccess, errorCallback);
}
A declared function does
function start() {
console.log('requesting local stream');
startButton.disabled = true;
getUserMedia(constraints, gotStreamSuccess, errorCallback);
}
How can I write
startButton.onclick = start;
so that it works with a function expression?
Thanks
In short, use function declarations when you want to create a function on the global scope and make it available throughout your code. Use function expressions to limit where the function is available, keep your global scope light, and maintain clean syntax.
A function call is an expression containing the function name followed by the function call operator, () . If the function has been defined to receive parameters, the values that are to be sent into the function are listed inside the parentheses of the function call operator.
The difference is the first one has the parentheses and the second one doesn't.
Use a function expression when:you need a function that isn't hoisted. the function should only used when it is defined. the function is anonymous, or doesn't need a name for later use. you want to control when the function is executed, using techniques like immediately-invoked function expressions (IIFE)
I would agree with you that it's a hoisting issue, you'll have to look within your code to hoist it appropriately before setting startButton.onclick = start;
.
Here's what MDN has to say about the syntax:
It specifically mentions that the function can either be declared or expressed. Which, to me, leads again to the hoising, because function declarations are automatically hoisted.
The MDN for onclick
uses a function declaration. I changed the example in this JSFiddle to use a function expression, as you would like to use. With proper hoisting, it is calling the correct method when you click the button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With