I'm trying to understand object creation in javascript and I understand that we have a few ways to accomplish it: Object Literal, Factory and Constructor.
/***********************************************/
/***********************************************/
// Literal - Singleton
const obj_lit = {
log_lit: function() {
//console.log("Obj Literal");
document.write("Obj Literal<br>");
}
};
obj_lit.log_lit();
/***********************************************/
/***********************************************/
// Factory - Explicit Return
function objFac() {
return {
log_fac: function() {
//console.log("Obj Factory");
document.write("Obj Factory<br>");
}
};
}
const obj_fac = objFac();
obj_fac.log_fac();
/***********************************************/
/***********************************************/
// Constructors - Implicit Return
function ObjCon() {
this.log_con = function() {
//console.log("Obj Constructor");
document.write("Obj Factory<br>");
}
}
const obj_con = new ObjCon();
obj_con.log_con();
I'm actually using the console, but in jsfiddle I output via doc write
The thing is that obj literal and factory we don't go through a constructor comparing to the way we explicitly do with obj constructor type. So far so good, but when in the console I check both obj literal and factory, they indeed have a constructor [native code]
This is what I get in the console:
obj_lit.constructor
ƒ Object() { [native code] }
obj_fac.constructor
ƒ Object() { [native code] }
obj_con.constructor
ƒ ObjCon() {
this.log_con = function() {
console.log("Obj Constructor");
}
}
So what really are those 2 native constructors for obj_lit and obj_fac?
and is the js engine actually creating the obj_lit and obj_fac via an internal 'new' keyword?
and wouldn't it break the whole concept of using literal and factories when we don't want to go for the classic way of creating objects via constructors?
So what really are those 2 native constructors for obj_lit and obj_fac?
{}
is equivalent to new Object
.
and is the js engine actually creating the obj_lit and obj_fac via an internal 'new' keyword?
More or less. It's an implementation detail.
and wouldn't it break the whole concept of using literal and factories when we don't want to go for the classic way of creating objects via constructors?
No.
Prototypal inheritance is a fundamental feature of JavaScript.
It will only break things if you start modifying the object prototype. If you don't want to make use of the OO features of JS then you wouldn't be doing that.