Just two ways of acomplish the same?

function User(name, age) {
  this.name = name;
  this.age = age;
}
let person = new User("Jack", 28);

and

const user = function (name, age) {
      return {name: name, age: age};
};
let person = user("Jack", 28);

Can we call the second way a constructor too? Any difference?

I didn’t know we could create objects this way, I got it from the " ES6: Write Concise Object Literal Declarations Using Object Property Shorthand" challenge and tweeked it a little to see what was happening and was surprised to see this way of create objects from function expressions, because never saw it till now or not that I remember.

I believe the second function is often referred to as a factory function (i.e. a function that returns an object).

The new operator will create the object for you and return it (plus do some extra stuff).

Are both constructors? Well in the sense that they both create an object and return it, yes. Not so sure I would consider it correct semantic to call the second a constructor, or at least it might be confusing to call it that.

The second one returns a plain object. The point of classes is that you create new types of things, first one creates an object of type User

2 Likes

Yes, I see it. With the second one, we access to things like methods of the prototype of User.

Now it makes sense, thank you!

Right, I guess I should have addressed the actual question. You already got the answer. No, they do not accomplish the same thing.

As for if you can call them both constructors. I wouldn’t say that a function that returns an object is automatically a constructor. The word constructor implies more than just returning an object.

1 Like