function Person(age,name){
this.name = name;
this.age = age;
this.speak = function(){...}
}
function Person(age,name){
var p = {}
p.name = name;
p.age = age;
p.speak = function(){...}
return p;
}
The only difference I see is that using the first one you must call with new to let the language know its constructing a new object, is it essentially just constructing an object where 'this' refers to the new object being created??
i.e same as doing this.
{
age: 12,
name: "mark",
speak: function(){...}
}
where as the second returns an object so you can just write
Person(12,"mark")
instead of
new Person(12,"mark")
So I guess my question is, is there anything wrong with using the second version and are the differences I stated correct and are they the only differences between the two?
The first one:
function Person(age,name){
this.name = name;
this.age = age;
this.speak = function(){...}
}
instanceof Person
new
.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;
}
instanceof
.new
and would still work (the system-created new object would just be discarded).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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With