0

I'm learning javascript and I'm confused with this definition. I look up in ECMA and it defines constructor as

function object that creates and initializes obejects.

So, can any function object be called constructor?

franose
  • 35
  • 5
  • a constructor can be thought as kind of template that defines of how an object is created. A function object might create an object, but it can differ from a constructor nonetheless at this point. – Blauharley Aug 21 '17 at 15:01
  • If you go by the spec, there's a part where it says: *A function object is not necessarily a constructor and such non-constructor function objects do not have a [[Construct]] internal method.* Examples exist such arrow functions, methods, Function.prototype, generator functions and async functions which are not constructors. – MinusFour Aug 21 '17 at 15:13

2 Answers2

1

In js its common to call a function constructor if its aim is to be called with the new operator:

var me = new Human;//Human is a constructor

However, human languages are not that strictly defined, so you can probably use it always, you just need to have good arguments for your usage. A good arguable case:

function Animal(name){//actually rather a factory function
  return {name};
}

var cat = new Animal("bob");//and now ? :/
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • *"actually rather a factory function"* That's what I thought initially too, but Wikipedia has this little remark: *"formally a factory is a function or method that returns objects of a varying prototype or class"*. So it seems one typically would only consider a function a factory if it returns different "kinds" of objects? It's all semantics really... – Felix Kling Aug 21 '17 at 15:06
  • @felix kling now it gets tricky ;) – Jonas Wilms Aug 21 '17 at 15:07
0

So, can any function object be called constructor?

But not every function creates or initializes objects. Consider this example:

function add(a, b) {
   return a + b;
}

This function only adds two values.

What is constructor? What kind of function object can be called constructor?

I'd argue that only functions that are intended to be called with new are supposed to be considered "constructors" (that includes functions created via class).

However, you can also create objects without calling a function with new:

function getPerson(name) {
   return {name: name};
}

Whether or not you consider such functions constructors is probably subjective.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143