Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onclick with a function expression rather than a declared function?

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

like image 494
javascriptttt Avatar asked Dec 18 '14 21:12

javascriptttt


People also ask

Should I use function declaration or function expression?

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.

How do you call a function expression?

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.

What's the difference between onclick ={ () => function ()} and onclick function?

The difference is the first one has the parentheses and the second one doesn't.

Why would you use a function expression?

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)


1 Answers

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: Syntax for on click

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.

like image 91
Adam Avatar answered Oct 08 '22 16:10

Adam