Thursday, December 3, 2015

JavaScript: Prototype Object Vs Reference Object Explained

What is an Object?
It is a set of key and value pairs. You can use any number of keys with any name as long as it is a String. And each key can be associated with any value, those values can be of any Types, such as: Primitive Types, Function Objects and object itself.
var myObject = {
  a: undefined, //Primitive
  b: null, //Primitive
  c: true, //Primitive
  d: "foo", //Primitive
  e: 4.33, //Primitive
  f: function bar() { /**/ }, //Object
  g: {
    h: baz
  } //Object
}

The difference:

In case of Objects - values are passed by reference, and the changes are bi-directional:
var a = { x: 1, y: 2}
var b = a;
console.log(b); // Object {x: 1, y: 2} 

//
b.x = 10;
console.log(a.x); // 10

//
a.y = 20;
console.log(b.y); //20

While in Primitive - the values are passed by value, and the changes are uni-directional:
//Prototype Object
var object1 = {x: 11, y: 22};
var object2 = Object.create(object1);
console.log(object2); //Object {}

//
object2.x = 100; 
console.log(object1.x); //11 
console.log(object2.x); //100 

//
object1.y = 200; 
console.log(object2.y); //200 
console.log(object1.y); //200 

Fiddle: http://jsfiddle.net/sL6q0742/