JSFiddle - React, Tailwind, and code Playground
by mendesjuan
JavaScript
function Class() {
this.obj2 = {c: 'c'}
}
Class.prototype = {
primitive: 'a',
obj: { a: 'a' },
arr: [1,2,3]
};
var inst1 = new Class();
var inst2 = new Class();
// this is ok: inst1 gets 'b', inst2 keeps 'a'
inst1.primitive = 'b';
console.log(inst1.primitive);
console.log(inst2.primitive);
// the two instances share the same instance of obj
// which may be unexpected
inst1.obj.a = 'b';
console.log(inst1.obj);
console.log(inst2.obj);
// same for arrays (since array is object)
inst1.arr.push(4);
console.log(inst1.arr);
console.log(inst2.arr);
// to get around this, create the child objects in constructor
// now changing obj2 in record1 does not affect record2
inst1.obj2.c = 'd';
console.log(inst1.obj2);
console.log(inst2.obj2);