Reputation: 61
How are they different and why would you use one over the other?
For example:
function setupOptionsObj(num) {
return {
data: num,
func: function() {
return num * 10
}
}
}
function setupOptionsConstructor(num) {
this.data = num;
this.func = function() {
return num * 10
}
}
var one = setupOptionsObj(123)
var two = new setupOptionsConstructor(123)
console.log(one.func());
console.log(two.func());
Thank you :)
Upvotes: 0
Views: 52
Reputation: 781741
setupOptionsObj()
returns a plain object.
new setupOptionsConstructor()
returns an object whose prototype is setupOptionsConstructor.prototype
.
Prototypes allow you to add methods and properties that apply to all objects created by that constructor. This is the basis of JavaScript's prototype-based object-oriented programming.
For example, below we only have one foo
function, not one in every object.
function setupOptionsConstructor(num) {
this.data = num;
}
setupOptionsConstructor.prototype.func = function() {
return this.data * 10
};
var two = new setupOptionsConstructor(123);
var three = new setupOptionsConstructor(456);
console.log(two.func());
console.log(three.func());
Upvotes: 2