First:
function Person(age,name){ this.name = name; this.age = age; this.speak = function(){...} }
- Is the named constructor function.
- Will work with
instanceof Person - Easier to do mixins or classic Javascript inheritance with
- Can use a prototype for methods that can consume less memory or create an object faster if there are many methods.
- It can also be designed to work without the need for
new . - More akin to how the new ES6
class and extends syntax works, which is likely to contain a lot of Javascript in the future.
Second:
function Person(age,name){ var p = {} p.name = name; p.age = age; p.speak = function(){...} return p; }
- Factory function. It creates a shared object, assigns properties to it, and then returns the object.
- It can be inherited from, but not in a classic way, just by another factory function that knows how this object works. Some types of myxin inheritance cannot handle this structure.
- Doesn't work with
instanceof . - Do not use prototype methods and do not use.
- It can be called using
new and will still work (the new object just created by the system will be discarded). - It can create any objects. It can even branch out on the basis of the arguments passed in or the environment and create objects of a different type based on some logic. Technically, you can do this with the first style as well, but it is inefficient because the interpreter creates a certain type of object, and then you return something else, creating the original object that was created to then collect garbage. So, if you are going to create several different types of objects, the second method will be more efficient in doing so.
Apart from these differences, they will work basically the same way, and nothing will be “wrong” with any technical method.
There are supporters of both styles of programming in Javascript, and some say that there are situations when one of them is more appropriate than the other, and vice versa. I suggest you create a couple of subclasses for this object in order to clear some of the differences in programming, because subclasses will also work differently.
If you want to search for other articles on this topic, this is basically a “constructor function versus factory function in Javascript”, which is sometimes rejected into the argument for / against using .prototype , but also also suitable for your topic.
Here are some articles on this topic (which cover the gamut of opinions):
JavaScript constructor functions Vs factory Functions
Javascript Object Creation Templates
In defense of JavaScripts constructors
Constructor function vs factory function
Factory constructor template
Some Useful JavaScript Object Creation Templates
Constructors are bad for JavaScript
Constructors vs factories