First I will give you some theory. The Javascript function is a dynamic object similar to
Object . It has properties and methods and can be added at runtime (hence dynamic). This keyword is tied to a newly created object, and therefore what you do above actually creates new properties on the fly when you first pass your values ββ... which is good, but not entirely clear to another reader.
Each object and function created by the user has a link to a "hidden" Prototype object. This is an anonymous object (not accessible by name) created by the JavaScript runtime, and is passed as a reference to the user object through the prototype property. The Prototype object also has a reference to the user object through its constructor property. Combining all this together, you can now consider functions as class constructors that are created for you for each function that you have, and which can be accessed through the function prototype property. Thus, you can add fields to the Prototype object directly like this:
function BudgetItem(spent) { this.spent = spent } BudgetItem.prototype.spent = 0; BudgetItem.prototype.setSpent = function(spent) { this.spent = spent }; BudgetItem.prototype.getSpent = function(){ return this.spent };
Another problem is inheriting and passing parameters to the constructor. Again, your version is valid, but you lose the ability to transfer spent and budget values ββwhen initializing BudgetType. What would I do, forget the prototypes and go:
function BudgetType(type, spent) { var instance = new BudgetItem(spent); instance.type = type; return instance; }
This is close to what Scott Soyet suggested, but more powerful. Now you can pass both parameters (and more) and have a more complex inheritance tree.
Finally, you can create private (or pseudo-private, more accuretly) properties by providing the getter with an otherwise automatic variable (which is passed as an argument or initialized inside a function). This is a feature of the language, and it works like this:
function BudgetType(type, spent) { var instance = new BudgetItem(spent); instance.getType = function() { return type; } return instance; }
Now you can access the "type" passed in the constructor, obj.getType (), but cannot override the initial value. Even if you define obj.type = 'New Value', getType () will return the original parameter passed as it has a link to another context that was created when the object was initialized and was not released due to closure.
Hope this helps ...