I have a JavaScript question. Imagine a virtual pen. There are many different possible nibs the pen can have, although the pen can only have one nib. I want to create a pen object and then assign it a nib. The nib needs to access the properties and methods of the pen.
This is probably a well-known design pattern. What is the name of this design pattern?
function Pen() {
var p1=5;
this.nib=null;
}
function Nib1() {
// needs access to p1.
}
function Nib2() {
// needs access to p1.
}
var p = new Pen();
var n1 = new Nib1();
p.nib = n1;
// n1 needs access to p1
-
1I honestly believe there is no such pattern because it is not a good design at all. If anything i would consider this an antipattern. It creates circular dependencies between those classes (because you say Nib needs access to Pen, but why?), which is always a bad thing. Things like Strategy pattern are supposed to address such problems.K. Kirsz– K. Kirsz2017年07月07日 18:44:13 +00:00Commented Jul 7, 2017 at 18:44
-
1What did you mean by "needs access to p1", generally the access is unidirectional to avoid circular dependency whenever possible (en.wikipedia.org/wiki/Circular_dependency). Maybe these thoughts on OOP concepts would help you ? (adobe.com/devnet/actionscript/learning/oop-concepts/… or stackoverflow.com/questions/2218937/…) I have a feeling you're just looking for "Composition" , where Pen has-a Nib, and Nib depends on some information that Pen passes into Nib's functions.K.F– K.F2017年07月07日 18:49:25 +00:00Commented Jul 7, 2017 at 18:49
-
I'm not sure if you're making a strange analogy or you want to create a pen in js. You typically want to stay away from this type of co-dependant relationship...try looking at functional programming and closure. It's a solid way to use JS. Going down the whole OOP route with JS can get messy pretty fast.Matthew Brent– Matthew Brent2017年07月07日 18:52:45 +00:00Commented Jul 7, 2017 at 18:52
-
I wouldn't say this is a JavaScript question so much as it is a general design question - this is probably a better fit for softwareengineering.stackexchange.comTheHans255– TheHans2552017年07月07日 19:07:16 +00:00Commented Jul 7, 2017 at 19:07
-
1"Name that thing" doesn't make for a very good question on SO. Perhaps you could describe your specific problem instead?Robert Harvey– Robert Harvey2017年07月07日 19:09:17 +00:00Commented Jul 7, 2017 at 19:09
1 Answer 1
It sounds a bit like using a constructor. This chapter describes a similar situation but with rabbits instead of pens: http://eloquentjavascript.net/06_object.html#constructors.
The pen would be the constructor:
function Pen(nib) {
// shared scope
this.nib = nib;
}
Then you can create
var bluePen = new Pen(blue)
... Although I guess it's slightly different because you're describing a single pen and with the constructor you can end up with multiple instances.