// prototypes
// inheritance. The concept of an object being "of type" another
// e.g. Car IS A machine. Inheritance is thus called "IS A" relationship.
// This is also called Parent-Child relationship.
// contrast this with "HAS A" which implies containership e.g.
// A House HAS A TV.
// In javascript, every object "has" a parent. An object cannot "access"
// its parent, but if the parents has any properties, the child has access
// to those properties. The child calls its parent, its "prototype". This
// is the concept called "prototype" i.e. every child has a prototype -
// which is its parent. Note again. THERE IS NO WAY FOR AN OBJECT TO ACCESS
// ITS PROTOTYPE. THIS IS JUST A CONCEPT. That being said, javascript
// also has a keyword called "prototype". This keyword can only be used by
// constructor functions.
function ObjectCreator(arg) {
this.oneElement = "oneElement: " + arg;
}
var oneObject = new ObjectCreator("1");
console.log("oneObject.oneElement: " + oneObject.oneElement);
console.log("oneObject.parentElement: " + oneObject.parentElement);
var parentObject = {
parentElement: "I come from parent Element"
};
// set the prototype keyword for the constructor function
ObjectCreator.prototype = parentObject;
// new object has properties contained by the parent
var twoObject = new ObjectCreator("2");
console.log("twoObject.oneElement: " + twoObject.oneElement);
console.log("twoObject.parentElement: " + twoObject.parentElement);
var anotherParent = {
parentElement: "anotherParentElement"
};
ObjectCreator.prototype = anotherParent;
// an object that was already created does not get changed when the
// constructor function changes its prototype
console.log("twoObject.oneElement: " + twoObject.oneElement);
console.log("twoObject.parentElement: " + twoObject.parentElement);
// new objects created with constructor, however, get the new parent
var threeObject = new ObjectCreator("3");
console.log("threeObject.oneElement: " + threeObject.oneElement);
console.log("threeObject.parentElement: " + threeObject.parentElement);
// Javascript inheritance is "alive" unlike most other languages. So
// if you change the parent, the child will see the change!
anotherParent.parentElement = "I am changing";
console.log("threeObject.parentElement: " + threeObject.parentElement);
// You cannot access the parent using the prototype keyword. It is available only
// to constructor functions.
console.log(threeObject.prototype);