You have essentially made all but objInfo()
in bab
obsolete, since objInfo()
simply returns exactly what is passed into it.
In your specific case, objInfo("simba")
doesn't work since objInfo()
simply returns the string "simba"
:
...
// Share diet publicly
this.objInfo = function(name) { // <-- If name == "simba"
return name; // <-- This will return "simba" not the Object simba!!!
};
};
alert(bab.objInfo('simba').diet); // This will check for the diet property of
// the string "simba". So it won't work.
However there is a larger problem, as I mentioned before. objInfo()
simply returns exactly what is passed into it!
Try out these examples:
alert(bab.objInfo('simba')); // This will alert "simba"
alert(bab.objInfo('noodles')); // This will alert "noodles"
alert(bab.objInfo(window).innerWidth); // This will give you the innerWidth of
You have essentially "short circuited" your entire bab
object. Only the objInfo
method "does" anything.
This is how I would do it:
// Namespace all my code
var bab = new function() {
var cat = function() // Declare cat object
{
var protected = {}; // Protected vars & methods
protected.eyes = 2;
protected.legs = 4;
protected.diet = 'carnivore';
return protected; // Pass protected to descendants
}
var lion = function()
{
var protected = cat(); // Make lion a subclass of cat
var public = {}; // Public vars & methods
public.legs = protected.legs; // Make 1 protected var public
public.mane = true;
public.origin = 'Africa';
public.diet = 'people'; // has priority over cat's diet
return public; // Make public vars available
}
var simba = lion(); // Create an instance of class lion
simba.diet = "Asparagus"; // Change simba, but not lion
// Get property of choice
this.objInfo = function(property) {
return ("Simba: " + simba[property] +
" - Lion (this is usually private. Shown for testing.): " +
lion()[property]);
};
};
alert(bab.objInfo("diet"));
I used functional inheritance in the above. I find it simpler to work with and it makes good use of the classless nature of Javascript's Object Oriented persona.
As test output, I returned directly from lion
... which you would not usually do, just to show that changing Simba
doesn't change lion
. You can tell that the lion
's diet has priority over the cat
's diet, just like you wanted.
The trick is to package your protected
and public
variables and methods in returned objects, and don't forget that you can also create methods in you felines.