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?
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?
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 ? :/
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.