3

I'm confused as to what the purpose or use cases are for functions being able to have method calls in JavaScript. I understand that functions are considered objects and thus can have their own properties and therefore functions, but it seems to me like it is still a little bit different than what I would call a standard object. For example, why would i ever do this...

var myFunction = function(){...};
myFunction.method = function(){...};

Instead of creating an object and having one or more function properties like the following...

var obj = {method: function(){}};

And if we were to console.log each we get the following...

console.log(myFunction);
console.log(obj);
------------------------------------------
{ [Function] secondFunction: [Function] }
{ method: [Function] }

I'm trying to learn the Express.js framework currently and it seems like it makes heavy use of this concept. What is the point? Is this what is meant by a top level function?

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
4Matt
  • 241
  • 1
  • 7
  • 1
    maybe this two answers can be helpful http://stackoverflow.com/a/15285702/2418529 http://stackoverflow.com/a/155655/2418529 – Nico Jul 26 '16 at 00:37
  • Thanks for the response, however I already understand the difference between a function a method. I think my confusion stems from the same principle that a square is technically a rectangle but a rectangle is not necessarily a square. In the case of JavaScript, a function is an object but an object isn't necessarily a function. The difference is that a function object can be invoked. What is the point of this functionality? What are the use cases? – 4Matt Jul 26 '16 at 00:52

1 Answers1

4

In the case of express, this enables the top-level API being callable and access to other contents of the module.

var express = require('express');

var app = express();
app.use(express.static('/root'));

var router = express.Router(); // etc...

This is pretty common if the main export of a module is a "constructor" of some sort, and the author also wants to expose additional things by attaching to that same top-level export.

Jacob
  • 77,566
  • 24
  • 149
  • 228