Is there any difference in how these functions operate? The first one is more typically of what I think about when thinking of a constructor.
Example 1: using this to name and set properties. Then using new to create a new Book object.
function Book(name, numPages) {
this.name = name;
this.numPages = numPages;
}
var myBook = new Book('A Good Book', '500 pages');
Example 2: returning a object by using new and just calling the function itself.
function Movie(name, numMinutes) {
return { name:name, numMinutes:numMinutes };
}
var best = new Movie('Forrest Gump', '150');
var other = Movie('Gladiator', '180');
I guess what I'm trying to figure out is if these are different in the way they create an object? If so is one better than the other? Are there different situations where one would work better over the other?
Basically, when you use
new, the JS engine makes a brand new object for you and injects that as the value ofthis. It also automatically gives you any methods attach to the prototype of the constructor. Using a constructor also allows you to check if an object is aninstanceofsomething more easily.Everything that
newoffers you can be attained through other methods but requires more manual labor.The second method, factories, tend to work better for unit testing, custom object creation and functional programming. It works better for unit testing because if you have a factory producing all of your objects, you can just replace that factory with a mock-up to test different cases.
As for when you use either, it all depends. Some people don't use
newat all. Others exclusively usenew. It all depends on if you need any of the things listed above, how much control you need over the creation of objects, when you want to usethisor not, etc. In the end, it's all a matter of preference.