Working code
That will work. But you should know that when you call:
var f = new Family("Doe");
f.People
is just an object constructor, not an instance of any other object. You will need to create an instance as well:
f.members = new f.People(3);
You have a constructor inside your instance that is pretty confusing.
Best approach
Thus, it would be better if you pressed your prototypes as follows:
var Family = function(name) { this._Name = name; this.getName = function() { return this._Name; }; }; Family.People = function(num) { this._Number = num; this.clearNumber = function() { this._Number = 0; }; };
This actually makes the class inside the class (and not inside the instances). Thus, the top lines will be called as follows:
var f = new Family("Doe"); f.members = new Family.People(3);
The scan for instance f
will look like this:
f _Name getName() members _Number clearNumber()
Private variables
var Family = function(name) { var _name = name; this.getName = function() { return _name; }; }; Family.People = function(num) { var _num = num; this.getNumber = function() { return _num; } this.clearNumber = function() { _num = 0; }; };
Thus, we make variables private and accessible only internally, so they cannot be manipulated externally. You should always use functions to control them. This makes it more reliable, especially when there are certain business rules related to variable values.
var f = new Family("Doe"); f._name; // this is undefined because "_name" is private closure variable
The sweep of an instance of f
will now look more like an instance of a class object:
f getName() members getNumber() clearNumber()
Robert Koritnik
source share