So I've read up and down on the topic of combination inheritance in JavaScript. I get that the intent is to use prototype chaining for to inherit properties and methods-- and use constructor stealing to inherit instance properties.
I've provided an example that is boggling me and preventing me from fully understanding this concept.
In a nutshell, I create a SuperColors parent function that passes along its properties to SubColors by a call() execution in the SubColors constructor method. As I understand it, this should allow the instance (instance1) to have its own color properties as I've demonstrated.
Here's the quirky part. I delete the instance1's property of colors. This should mean that when I push new colors they should manipulate SuperColors color property to the full rainbow. Then when I create a new instance (instance2) of SubColors they should inherit the rainbow.
They don't though. If we look at the instance2 in console.log() the colors were instantiated with "Red,Orange,Yellow", even though we can clearly see that SuperColor's color property has the entire rainbow.
This doesn't make sense to me-- am I understanding prototype inheritance incorrectly or is this a weird quirk of the language that is unexpected?
function SuperColors() {
this.colors = ["red", "orange", "yellow"];
}
SuperColors.prototype.sayColors = function () {
alert("SuperColors " + this.colors);
};
function SubColors() {
//inherit properties
SuperColors.call(this);
}
// inherit methods
SubColors.prototype = new SuperColors();
SubColors.prototype.sayRainbow = function () {
alert(this.colors + "a whole rainbow!");
};
// create an instance of SubColors
var instance1 = new SubColors();
// push colors to colors property on instance
instance1.colors.push("green", "blue", "purple");
alert(instance1.colors); // "red, orange, yellow, green, blue, purple"
instance1.sayColors(); // "SuperColors red,orange,yellow,green,blue,purple";
// delete instance of colors
delete(instance1.colors);
console.log(instance1);
// this should manipulate SuperColor's constructor of colors
instance1.colors.push("green", "blue", "purple");
// instantiate a new SubColor object that should inherit SuperColor's entire rainbow
var instance2 = new SubColors();
alert(instance1.colors);
alert(instance2.colors); // WHY ISN'T THIS THE ENTIRE RAINBOW? It should have been instantiated with SuperColor's modified colors.
console.log(instance2); // Shows that SuperColors.colors has the rainbow, but the instance has only 3 colors?