The first one:
function Person(age,name){
this.name = name;
this.age = age;
this.speak = function(){...}
}
- Is a named constructor function.
- Will work properly with
instanceof Person
- Is easier to do mixins or classic Javascript inheritance with
- Could use the prototype for methods which may consume less memory or be faster to construct an object if there are lots of methods
- Could also be designed to work without requiring
new
.
- Is more akin to how the new ES6
class
and extends
syntax works which is likely how a lot of Javascript will be written in the future.
The second one:
function Person(age,name){
var p = {}
p.name = name;
p.age = age;
p.speak = function(){...}
return p;
}
- Is a factory function. It creates a generic object, assigns properties to it and then returns the object.
- It could be inherited from, but not in a classic way only by another factory function that knows how this object works. Some types of inheritance of mixins are not as doable with this structure.
- Will not work with
instanceof
.
- Does not and cannot use the prototype for methods.
- Could be called with
new
and would still work (the system-created new object would just be discarded).
- Can create any kind of object. It can even branch based on the arguments passed or environment and create a different kind of object based on some logic. Technically you can do this with the first style too, but it's inefficient because the interpreter creates a specific type of object and then you would return something else causing the original object that was created to then be garbage collected. So, if you're going to create multiple different kinds of objects, the second method would be more efficient at that.
Outside of these differences, the two will mostly function the same and there is nothing technically "wrong" with either method.
There are advocates for both styles of programming in Javascript and some would say there are situations where one is more appropriate than another and vice versa. I'd suggest you build a couple subclasses for this object to flush out some more of the programming differences because the subclasses will also work differently.
If you want to search for other articles on the topic, this is basically a "constructor function vs. a factory function in Javascript" which will sometimes stray into the argument for/against using the .prototype
, but also tends to cover your topic too.
Here's are some articles on that specific topic (which cover a gamut of opinions):
JavaScript Constructor Functions Vs Factory Functions
Javascript object creation patterns
In defense of JavaScript’s constructors
Constructor function vs Factory functions
Factory constructor pattern
Some Useful JavaScript Object Creation Patterns
Constructors Are Bad For JavaScript
Constructors vs factories