I'm trying to wrap my mind around Object Linking Other Objects to write a Node module. This is what I have so far (inspired by this answer):
'use strict'
// Composable prototype object
var parent = {
publicVar: 1,
doSomething() {
return externalMethod(this.publicVar) + 10
}
}
// Composable prototype object
var child = {
doSomethingChild() {
return this.publicVar + 20
}
}
// an external method
function externalMethod(arg) {
return arg
}
// the parent factory
function Parent() {
let privateVar = 2
return Object.assign({
getPrivate() {
return privateVar
}
}, parent)
}
// the child factory
function Child() {
let privateVar = 4
let parent = Parent() // call to the Parent factory
return Object.assign(parent, child, {
getPrivateChild() {
return privateVar
}
})
}
// Node export
module.exports = {
Parent: Parent(),
Child: Child()
}
Later, I will require the module like this:
Parent = require('./my-module').Parent
Child = require('./my-module').Child
Parent.getPrivate() // 2
Parent.doSomething() // 11
Child.getPrivateChild() // 4
Child.doSomethingChild() // 21
I'm afraid there might be a more elegant way of doing this using OLOO. My main concern is that I think I should be doing let parent = Object.create(Parent)
in the Child factory, but if I do that it doesn't work.
So, 1) am I missing something and 2) can this be refactored?
I'm trying to wrap my mind around Object Linking Other Objects to write a Node module. This is what I have so far (inspired by this answer):
'use strict'
// Composable prototype object
var parent = {
publicVar: 1,
doSomething() {
return externalMethod(this.publicVar) + 10
}
}
// Composable prototype object
var child = {
doSomethingChild() {
return this.publicVar + 20
}
}
// an external method
function externalMethod(arg) {
return arg
}
// the parent factory
function Parent() {
let privateVar = 2
return Object.assign({
getPrivate() {
return privateVar
}
}, parent)
}
// the child factory
function Child() {
let privateVar = 4
let parent = Parent() // call to the Parent factory
return Object.assign(parent, child, {
getPrivateChild() {
return privateVar
}
})
}
// Node export
module.exports = {
Parent: Parent(),
Child: Child()
}
Later, I will require the module like this:
Parent = require('./my-module').Parent
Child = require('./my-module').Child
Parent.getPrivate() // 2
Parent.doSomething() // 11
Child.getPrivateChild() // 4
Child.doSomethingChild() // 21
I'm afraid there might be a more elegant way of doing this using OLOO. My main concern is that I think I should be doing let parent = Object.create(Parent)
in the Child factory, but if I do that it doesn't work.
So, 1) am I missing something and 2) can this be refactored?
Share Improve this question edited May 23, 2017 at 12:34 CommunityBot 11 silver badge asked Mar 5, 2017 at 17:29 nachocabnachocab 14.5k21 gold badges104 silver badges159 bronze badges 10-
1
I'm not sure that the linked answer is a good example that should be followed. It claims that it does 'position over inheritance', but in fact it is just mix-in pattern. Which looks crippled in ES6, considering that we have classes. Do you have problems with classes and prototypal ineritance that you try to solve this way? Since the question has
ecmascript-6
tag, the obvious answer is 'don't do that in ES6'. – Estus Flask Commented Mar 5, 2017 at 18:18 - @estus Are you remending the use of ES6 classes? Several people make a good case against them: Kyle Simpson, Eric Elliott. How would you refactor this? – nachocab Commented Mar 5, 2017 at 22:00
- 1 For this case, absolutely. Two classes, two instances, there's nothing to think about. Once you mastered both ways and know how they affect design and performance, you can choose one or another - but most times you will choose classes, because they are effective and do the job. I find YDKJS series quite enlightening but also unreasonably opinionated. The said chapter bashes prototypes, while they are idiomatic to JS and may perform better IRL. – Estus Flask Commented Mar 5, 2017 at 22:13
-
1
You really should not export
Parent()
andChild()
instances but theParent
andChild
functions themselves. – Bergi Commented Mar 6, 2017 at 1:46 - 1 @nachocab If you export instances, they bee singletons, and all your plicated factory stuff could be replaced by a trivial object literal. – Bergi Commented Mar 6, 2017 at 11:34
4 Answers
Reset to default 9You absolutely should prefer position (including mixins) over single-ancestor class inheritance, so you're on the right track. That said, JavaScript doesn't have private properties as you might know them from other languages. We use closures for data privacy in JS.
For posable prototypes with real data privacy (via closure), what you're looking for is functional mixins, which are functions that take an object and return an object with new capabilities added.
However, in my opinion, it's usually better practice to do your functional inheritance using posable factories (such as stamps). AFAIK, Stampit is the most widely-used implementation of posable factories.
A stamp is a posable factory function that returns object instances based on its descriptor. Stamps have a method called .pose()
. When called the .pose()
method creates new stamp using the current stamp as a base, posed with a list of posables passed as arguments:
const binedStamp = baseStamp.pose(posable1, posable2, posable3);
A posable is a stamp or a POJO (Plain Old JavaScript Object) stamp descriptor.
The .pose()
method doubles as the stamp’s descriptor. In other words, descriptor properties are attached to the stamp .pose()
method, e.g. stamp.pose.methods
.
Composable descriptor (or just descriptor) is a meta data object which contains the information necessary to create an object instance. A descriptor contains:
methods
— A set of methods that will be added to the object’s delegate prototype.properties
— A set of properties that will be added to new object instances by assignment.initializers
— An array of functions that will run in sequence. Stamp details and arguments get passed to initializers.staticProperties
— A set of static properties that will be copied by assignment to the stamp.
Basic questions like “how do I inherit privileged methods and private data?” and “what are some good alternatives to inheritance hierarchies?” are stumpers for many JavaScript users.
Let’s answer both of these questions at the same time using init()
and pose()
from the stamp-utils
library.
pose(…posables: [...Composable]) => Stamp
takes any number of posables and returns a new stamp.init(…functions: [...Function]) => Stamp
takes any number of initializer functions and returns a new stamp.
First, we’ll use a closure to create data privacy:
const a = init(function () {
const a = 'a';
Object.assign(this, {
getA () {
return a;
}
});
});
console.log(typeof a()); // 'object'
console.log(a().getA()); // 'a'
It uses function scope to encapsulate private data. Note that the getter must be defined inside the function in order to access the closure variables.
Here’s another:
const b = init(function () {
const a = 'b';
Object.assign(this, {
getB () {
return a;
}
});
});
Those a
’s are not typos. The point is to demonstrate that a
and b
’s private variables won’t clash.
But here’s the real treat:
const c = pose(a, b);
const foo = c();
console.log(foo.getA()); // 'a'
console.log(foo.getB()); // 'b'
WAT? Yeah. You just inherited privileged methods and private data from two sources at the same time.
There are some rules of thumb you should observe when working with posable objects:
- Composition is not class inheritance. Don't try to model is-a relationships or think of things in terms of parent/child relationships. Instead, use feature-based thinking.
myNewObject
needsfeatureA
,featureB
andfeatureC
, so:myNewFactory = pose(featureA, featureB, featureC); myNewObject = myNewFactory()
. Notice thatmyNewObject
is not an instance offeatureA
,featureB
, etc... instead, it implements, uses, or contains those features. - Stamps & mixins should not know about each other. (No implicit dependencies).
- Stamps & mixins should be small. Introduce as few new properties as possible.
- When posing, you can and should selectively inherit only the props you need, and rename props to avoid collisions.
- Prefer modules for code reuse whenever you can (which should be most of the time).
- Prefer functional programming for domain models and state management. Avoid shared mutable state.
- Prefer higher order functions and higher order ponents over inheritance of any kind (including mixins or stamps).
If you stick to those guidelines, your stamps & mixins will be immune to mon inheritance problems such as the fragile base class problem, the gorilla/banana problem, the duplication by necessity problem, etc...
With ES6 classes, it is as simple as
class Parent {
constructor() {
this.publicVar = 1;
this._privateVar = 2;
}
getPrivate() {
return this._privateVar;
}
doSomething() {
return externalMethod(this.publicVar) + 10
}
}
class Child extends Parent {
constructor() {
super();
this._privateVar = 4;
}
doSomethingChild() {
return this.publicVar + 20
}
}
module.exports = {
parent: new Parent(),
child: new Child()
}
Depending on the roles of publicVar
and _privateVar
, they may be static properties.
The use of _privateVar
property isn't accidental. Usually _
naming convention (and possibly non-enumberable descriptor) is enough to designate the member as private/protected.
Object.assign
is ineffective as main inheritance technique in ES6, but can be used additionally to implement polymorphic inheritance.
After having read carefully all the posts and trying to understand the OP's problem, I think the OP's approach already was pretty close to a solid solution. After all, reliable encapsulation in JS mostly falls back to some closure based techniques. The pure object and factory based approach is lean too.
In order to fully understand the provided example, I did refactor it with being more explicit about naming the different posable parts, especially the "behavior" section. I also did not feel fortable with the child-parent relationship and with how to export the factories. But since such examples are mostly boiled down code, one has to guess as often the OP's real world problem.
This is what a running refactored code, that does preserve the OP's approach, could look like ...
// an external method
function externalPassThroughMethod(value) {
return value;
}
// some posable object based behavior
const withGetPublicValueIncrementedByTen = {
getPublicValueIncrementedByTen() {
return (externalPassThroughMethod(this.publicValue) + 10);
}
};
// another posable object based behavior
const withGetPublicValueIncrementedByTwenty = {
getPublicValueIncrementedByTwenty() {
return (externalPassThroughMethod(this.publicValue) + 20);
}
};
// the parent factory
function createParent(publicOptions = {}) {
var localValue = 2;
// `publicValue` via `publicOptions`
return Object.assign({}, publicOptions, withGetPublicValueIncrementedByTen, {
getLocalValue() {
return localValue;
}
});
}
// the child factory
function createChild(parent) {
var localValue = 4;
// `publicValue` via `parent`
return Object.assign({}, parent, withGetPublicValueIncrementedByTwenty, {
getLocalValue() {
return localValue;
},
getLocalValueOfParent() { // object linking other object ...
return parent.getLocalValue(); // ... by forwarding.
}
});
}
// // Node export
// module.exports = {
// createParent: createParent,
// createChild : createChild
// }
// some (initial) key value pair
const initalPublicValue = { publicValue: 1 };
const parent = createParent(initalPublicValue);
const child = createChild(parent);
console.log('parent.getLocalValue()', parent.getLocalValue()); // 2
console.log('parent.getPublicValueIncrementedByTen()', parent.getPublicValueIncrementedByTen()); // 11
console.log('parent.getPublicValueIncrementedByTwenty', parent.getPublicValueIncrementedByTwenty); // [UndefinedValue]
console.log('child.getLocalValue()', child.getLocalValue()); // 4
console.log('child.getLocalValueOfParent()', child.getLocalValueOfParent()); // 2
console.log('child.getPublicValueIncrementedByTen()', child.getPublicValueIncrementedByTen()); // 11
console.log('child.getPublicValueIncrementedByTwenty', child.getPublicValueIncrementedByTwenty()); // 21
.as-console-wrapper { max-height: 100%!important; top: 0; }
The next given example code takes the just provided refactored example but uses function based instead of object based mixins and factories that do create class based types instead of plain object (literal) based ones. Yet, both examples have in mon one and the same approach about how to handle encapsulation and position ...
// an external method
function externalPassThroughMethod(value) {
return value;
}
// some posable function based behavior
const withGetPublicValueIncrementedByTen = (function () {
function getPublicValueIncrementedByTen() {
// implemented once ...
return (externalPassThroughMethod(this.publicValue) + 10);
}
return function () {
// ... shared (same implementation) code.
this.getPublicValueIncrementedByTen = getPublicValueIncrementedByTen;
};
}());
// another posable function based behavior
const withGetPublicValueIncrementedByTwenty = (function () {
function getPublicValueIncrementedByTwenty() {
// implemented once ...
return (externalPassThroughMethod(this.publicValue) + 20);
}
return function () {
// ... shared (same implementation) code.
this.getPublicValueIncrementedByTwenty = getPublicValueIncrementedByTwenty;
};
}());
class Parent {
constructor(publicOptions = {}) {
function getLocalValue() {
return localValue;
}
var localValue = 2;
// `publicValue` via `publicOptions`
Object.assign(this, publicOptions);
withGetPublicValueIncrementedByTen.call(this);
this.getLocalValue = getLocalValue;
}
}
class Child {
constructor(parent) {
function getLocalValue() {
return localValue;
}
function getLocalValueOfParent() { // object linking other object ...
return parent.getLocalValue(); // ... by forwarding.
}
var localValue = 4;
// `publicValue` via `parent`
Object.assign(this, parent);
withGetPublicValueIncrementedByTwenty.call(this);
this.getLocalValue = getLocalValue;
this.getLocalValueOfParent = getLocalValueOfParent;
}
}
function createParent(publicOptions = {}) {
return (new Parent(publicOptions));
}
function createChild(parent) {
return (new Child(parent));
}
// // Node export
// module.exports = {
// createParent: createParent,
// createChild : createChild
// }
// some (initial) key value pair
const initalPublicValue = { publicValue: 1 };
const parent = createParent(initalPublicValue);
const child = createChild(parent);
console.log('parent.getLocalValue()', parent.getLocalValue()); // 2
console.log('parent.getPublicValueIncrementedByTen()', parent.getPublicValueIncrementedByTen()); // 11
console.log('parent.getPublicValueIncrementedByTwenty', parent.getPublicValueIncrementedByTwenty); // [UndefinedValue]
console.log('child.getLocalValue()', child.getLocalValue()); // 4
console.log('child.getLocalValueOfParent()', child.getLocalValueOfParent()); // 2
console.log('child.getPublicValueIncrementedByTen()', child.getPublicValueIncrementedByTen()); // 11
console.log('child.getPublicValueIncrementedByTwenty', child.getPublicValueIncrementedByTwenty()); // 21
.as-console-wrapper { max-height: 100%!important; top: 0; }
For pletion's sake, using Eric Elliott's answer turns out to be pretty simple:
var stampit = require('stampit')
function externalMethod(myVar) {
return myVar
}
parent = stampit().init(function({value}){
this.privateVar = 2
}).props({
publicVar: 1
}).methods({
doSomething() {
return externalMethod(this.publicVar) + 10
},
getPrivate() {
return this.privateVar
}
})
child = parent.init(function({value}){
this.privateVar = 4
}).methods({
doSomethingChild() {
return this.publicVar + 20
}
})
parent().getPrivate() // 2
parent().doSomething() // 11
child().getPrivate() // 4
child().doSomething() // 11
child().doSomethingChild() // 21