HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript traits implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptimplementationtraits

Problem

I wanted to step up my JS game, and move on from mostly closure based scripting, so I decided to write an application in node. I don't have much experience with prototype based programming, and I guess it's a little too early for ES6 (well, maybe with traceur).

During planning of my app I saw that often I'll need container behaviour. So, I know I could implement it with a class, but I thought: why not use trait-like thingy instead?

Gamemode.js, concrete class

'use strict';

var Script = require('../Script');

var Gamemode = module.exports = function () {
    Script.apply(this, arguments);
};

Gamemode.prototype = Object.create(Script.prototype);
Gamemode.prototype.constructor = Gamemode;


Script.js, abstract class

'use strict';

var helper = require("./helper");
var _ = require("lodash");

var Script = module.exports = function () {
    if (this.constructor === Script) {
        throw new Error("Can't initialize abstract class!");
    }

    var defaultDefinitions = {
        MAX_PLAYERS: '(500)'
    };

    _.merge(this, helper.collection("definition", defaultDefinitions));
};

Script.prototype.build = function () {
    return this.definitions;
};


helper.js

```
'use strict';

var _ = require("lodash");

var capitalize = function (string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
};

var container = function (singular, mutable) {
if (undefined === mutable) {
mutable = false;
}

var accessors = {},
methodSingular = capitalize(singular),
plural = singular + 's',
methodPlural = capitalize(plural);

accessors['get' + methodPlural] = function () {
return this[plural];
};

accessors['set' + methodPlural] = function (value) {
if (undefined === value) {
delete this[plural];
}

this[plural] = value;

return this;
};

if (mutable) {
accessors['add' + methodSingular] = function (item) {

Solution

Interesting question,

this code pass JSHint, it is readable, well organized and except for return definitions; (where did you declare definitions?) holds few mysteries to me.

Still, when I take a step back, why not simple use a bog standard Object? It seems as if you just re-invented the Object with few added benefits.

Context

StackExchange Code Review Q#71207, answer score: 2

Revisions (0)

No revisions yet.