I am trying to understand the real difference between keywords new
and Object.create()
Explaination:
a1
isfunction
whilea2
is anobject
a1
&a2
are havingkey1
as default property.key2
is being assigned after an instancebxx
is created from them. to check whetherbxx
is independent object itself or just a reference.
"use strict";
function a1() {
this.key1 = "value 1";
}
let a2 = {
key1: "value 1"
};
let b1new, b1obj, b2new, b2obj;
try {
b1obj = Object.create(a1);
} catch (e) {
console.error("Error a1: ", e.message)
}
try {
b1new = new a1();
} catch (e) {
console.error("Error a1: ", e.message)
}
try {
b2obj = Object.create(a2);
} catch (e) {
console.error("Error a2: ", e.message)
}
try {
b2new = new a2();
} catch (e) {
console.error("Error a2: ", e.message)
}
//let b = new a();
a1.key2 = "value 2";
a2.key2 = "value 2";
if (b1obj) {
console.log("b1obj.key1: ", b1obj.key1);
console.log("b1obj.key2: ", b1obj.key2);
}
if (b1new) {
console.log("b1new.key1: ", b1new.key1);
console.log("b1new.key2: ", b1new.key2);
}
if (b2obj) {
console.log("b2obj.key1: ", b2obj.key1);
console.log("b2obj.key2: ", b2obj.key2);
}
if (b2new) {
console.log("b2new.key1: ", b2new.key1);
console.log("b2new.key2: ", b2new.key2);
}
Output:
"Error a2: " "a2 is not a constructor"
"b1obj.key1: " undefined
"b1obj.key2: " "value 2"
"b1new.key1: " "value 1"
"b1new.key2: " undefined
"b2obj.key1: " "value 1"
"b2obj.key2: " "value 2"
Questions:
- Why can't use
new
on a2 ? - Why
b1obj.key1
isundefined
? - Why
b2obj.key2
is still referring to parent's property?