user606521
user606521

Reputation: 15434

`[Function]` and `[Function: Object]` - what is difference?

var Cls = function(){}
var inst = new Cls()
var obj = {}

console.log(inst.constructor)
console.log(obj.constructor)

outputs:

[Function]
[Function: Object]

What is difference between [Function] and [Function: Object]?

Upvotes: 1

Views: 52

Answers (2)

apsillers
apsillers

Reputation: 115940

A function can have an immutable name (which is independent of the name of any variable that might refer to the function). A function's name (if it has one) is part of its definition:

function NAME () { ... }

When Node's console.log logs a function, the output will include the function's name, if it has one.

Here, obj.constructor is the Object constructor, which happens to have the name Object (i.e., it is defined by function Object() { ... }). Your Cls function, however, does not have a name (i.e., it is defined by an anonymous function function() { }). If you give that function a name, you will see it reported by console.log:

var Cls = function thisIsTheNameOfCls(){}
var inst = new Cls()
var obj = {}

console.log(inst.constructor)
console.log(obj.constructor)

This produces the output:

[Function: thisIsTheNameOfCls]
[Function: Object]

Upvotes: 1

Short answer: Javascript doesn't have classes, it has functions that can be instantiated. var Cls is an anonymous function; Object is a named function.


Long answer:

Javascript functions can be instantiated to create objects, similarly to how classes can be instantiated in other formal object oriented languages.

That being said, what you're seeing is the result of your use of an anonymous function.

The first line of output simply shows the constructor for inst is a function. It doesn't have a name, therefore no name is shown; it is anonymous.

The second line is showing it was created from the Object function.

Here are two variations to better show my point:

var Cls = function Cls(){};
var inst = new Cls();

should now accurately show

[Function: Cls]

As well, you can also do

var obj = new Object();

which is similar to

var obj = {}

Upvotes: 3

Related Questions