oop - Container Class in Javascript -
total oop beginner , doing in javascript, forgive blatant dumbness on part:
i want keep track of dynamically created objects. believe solution problem use container class.
- is container class want?
- if yes, implementation correct?
branch objects dynamically generated.
branches objects contain branch objects array.
function branches() { function branch() { var _id; _id = math.round(math.random()*10); this.getid = function() { return _id; } } this.createbranch = function() { var branch = new branch; _branches.push(branch); } this.getbranches = function() { return _branches; } this.getbranchids = function() { var branch_list = this.getbranches(); var branch_ids = []; (var = 0; < branch_list.length; i++) { var branch_id = branch_list[i].getid(); branch_ids.push(branch_id); } return branch_ids; } var _branches = []; } // code test var test = new branches; (var = 0; < 7; i++) { test.createbranch(); } console.log("branch ids:\n" + test.getbranchids());
your code works (yay!) despite few simple problems (you're not generating unique ids each branch, example). if happy design chose, feel free take code code review. there tips improving code is.
to answer first, more conceptual question, you've written 1 way implement want. you've gone factory pattern here. you've written class, branches
, provides interface creating objects of class branch
.
createbranch
known factory method; handles creation of new object, , in case, keeping track of object in array. returns new object user can interact branch
object necessary.
one thing consider implementation branch
private, visible code inside branches
class. has few implications come mind:
- the way create
branch
object throughcreatebranch
factory- all
branch
objects tracked because of this
- all
- any properties of
branch
constructor (meaning,branch.property = value
) not accessible outside ofbranches
class.
this may want. if there no reason hide branch
constructor or prototype plain sight, i'd suggest other design patterns.
a strategy might use constructor properties. way, reduce code lot, , have 1 fewer class deal (but no factory methods):
function branch() { var _id = math.round(math.random() * 10); this.getid = function () { return _id; }; branch.branches.push(this); } branch.branches = []; branch.getids = function () { var ids = []; (var in branch.branches) ids.push(branch.branches[i].getid()); return ids; }; // test code (var = 0; < 7; i++) { new branch(); } console.log("branch ids:\n" + branch.getids());
Comments
Post a Comment