My problem is with objInfo(). How can I return an object via a passed-in variable? I’m trying to namespace my code and use private/public vars.
Bonus Q: How would you otherwise improve the code?
// Namespace all my code
var bab = new function() {
// Declare cat object
function cat()
{
this.eyes = 2;
this.legs = 4;
this.diet = 'carnivore';
return true;
}
// Declare lion object
function lion()
{
this.mane = true;
this.origin = 'Africa';
this.diet = 'people'; // has priority over cat's diet
return true;
}
// Make lion a subclass of cat
lion.prototype = new cat();
// Create an instance of class lion
var simba = new lion();
// Share diet publicly
this.objInfo = function(name) {
return name; // simba works, name doesn't
};
};
alert(bab.objInfo('simba').diet);
Note: Source is sampled from various places
Other than namespacing, it’s not clear to me what you’re trying to do, but I’ve included a code review of sorts under the divider below. More high-level comments first.
There are a couple of issues here. First off, you almost never want to write
new function() { }. It’s a very advanced technique that’s easy to get wrong (and very easy for anyone doing maintenance on the code to misunderstand). There’s an example of another, less-confusing way to get the same effect (plus some other benefits) below.Here’s an example of a namespaced module providing two “classes”,
CatandLion(I’ve made them initially-capped because that’s the usual convention: initial caps on constructor functions and initial lower case on non-constructor functions, just to make it easy to read code):(You can, of course, call
publicsanything else you want —pubs,p, whatever. It’s the equivalent ofthisin the outermost layer of yournew function() { }function, but less confusing.)But just replacing the prototype on
Lionis a bit simplistic. When you start getting into subclassing, there are several other things you want to look at doing. Here’s a blog post that details a fairly complete means of building classes, including subclassing, calling superclass functions, etc.In terms of looking something up by string, you can do that with brackets notation on any object:
Code review follows.
Here’s a code review: