2

When an object is created with the Construction Invocation Pattern, there is a constructor function in play with its prototype. So far, the purposes of each of these are all clear.

var Function_a = function(){
};

var a = new Function_a;

enter image description here

However, when a function is not intended to be a constructor why does javascript still generate its prototype? (It does according to my debugging)

In what scenarios this prototype, c/would be used in javascript if the function is not intended to be a constructor? Or, is it the case that the compiler doesn't know better, and just creates a prototype object anyway in case we want to use the function as a constructor?

var function_b = function(){};

enter image description here

Crocodile
  • 5,724
  • 11
  • 41
  • 67

1 Answers1

2

First of all, there is no JavaScript compiler (except perhaps the Closure Compiler etc., but that's still not a JavaScript compiler in the traditional sense of a compiler). There are only JavaScript interpreters.

Second, yes. JavaScript always creates a prototype object for every function that you create. That's just the way it is. Luckily, this doesn't make the language slow because of some very smart optimizations that JavaScript interpreters make use of (I hope). Either way, you really don't need to worry about it.

Ignorance is blss.

Third, nice diagrams. I drew some diagrams in a previous answer of mine, but they are horrible.


when a function is not intended to be a constructor why does javascript still generate its prototype?

It generates prototypes for every function.

In what scenarios this prototype, c/would be used in javascript if the function is not intended to be a constructor?

It's just a normal object. I suppose it can be used for just about anything. However, if people want to create an object then the usually just use object literals instead of messing about with useless prototypes created by JavaScript on the fly.

Or, is it the case that the compiler doesn't know better, and just creates a prototype object anyway in case we want to use the function as a constructor?

Yes.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299