5

Consider the piece of code below.
The type of exports is function. But we can still have exports.hello property. How is that possible??

const obj = {
    exports: {}
}
obj.exports = () => {
    console.log('invoked')
}
obj.exports.hello = () => {
    console.log('hello() invoked')
}
var output = `type of obj => ${typeof obj} #### 
type of obj.exports => ${typeof obj.exports} ####
obj.exporst.hello() is ${typeof obj.exports.hello}
`;
console.log(output);

The output is:

type of obj => object #### type of obj.exports => function #### obj.exporst.hello() is function

It is logical to have an exports object (typeof 'object') and have functions like exports.hello, exports.foo, etc. But how can we have exports itself as function and then have properties of exports?

deceze
  • 510,633
  • 85
  • 743
  • 889
Amirhosein Al
  • 470
  • 6
  • 18
  • 4
    javascript is a strange and a beautiful creation – N. Ivanov Jan 24 '18 at 10:44
  • Each function is an object as well - it has a constructor function (named as weird as possible, of course, - `Function`). Yes, `typeof` returns different value, but it's more about weirdness of `typeof` (consider `null` case). – raina77ow Jan 24 '18 at 10:46
  • Javascript by far isn't the only language with this trait. – deceze Jan 24 '18 at 10:51
  • Consider the much simpler case that every function has a number of build-in properties and methods by default, e.g. `foo.bind(bar)`, `foo.length`… https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype – deceze Jan 24 '18 at 10:55

3 Answers3

5

According to MDN documentation

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

And this is self sufficient to explain why you can have properties of a function

Check this link on the properties and method of function objects

to Summarize what the MDN documentation state

The global Function object has no methods or properties of its own. However, since it is a function itself, it does inherit some methods and properties through the prototype chain from Function.prototype.

In short a function is an instance of an Object

function myName() {
   console.log('myName')
}

console.log(myName instanceof Object);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
3

Functions are Objects. Anything you can do to an Object, you can do to a Function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

JavaScript is highly dynamic-typed language, so this behavior is not surprising. Just think about JavaScript functions as about objects which can be called.

Anton Tupy
  • 951
  • 5
  • 16