Are Javascript functions objects?

A Javascript function is also an object of type function. So it can be used as an object and can have member variables. Also note that every function also has a member variable prototype. Here are some code examples.

Using function as object example

This example is setting a variable f using a function expression and then setting a property of it.

<script type="text/javascript">
var f = function () {
}
f.v1 = "value1";
document.write("typeof(f)=" + typeof(f) + "<br/>");
document.write("==all properties==<br/>");
Object.getOwnPropertyNames(f).forEach(function(x) {
  document.write("key=" + x + " value=" + f[x] + "<br/>");
});
</script>
refresh

jQuery is also a function

Popular Javascript library jQuery is also function object and hence it is called as function sometimes ($("#id")) and it also have many member variables.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
  document.write("typeof($)=" + typeof($) + "<br/>");
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments