Jonah Jonah - 3 months ago 6
jQuery Question

Why can't functions be assigned to variables and keep their functionality?

This works:

var foo = $("#bar");
foo.html("Hello.");


This doesn't:

var foo = $("#bar").html;
foo("Hello.");


What breaks the functionality?

Answer

Well this should:

var bar = $("#bar");
var foo = bar.html.bind(bar);
foo("Hello.");

In your second example, the html function lost its calling context when you assigned it to the foo variable.

Comments