1

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?

2
  • 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. Commented Aug 21, 2017 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. Commented Aug 21, 2017 at 15:13

2 Answers 2

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 ? :/
Sign up to request clarification or add additional context in comments.

2 Comments

"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 now it gets tricky ;)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.