Avoiding name conflicts when composing objects

In JavaScript, you can create objects using a function extend.

For example, I can have a class observablethat provides a set of public methods ( get, push, set, increment, get, etc.)

In this case, the observation is also EventEmitter, so it also provides an additional set of public methods ( emit, on, removeListeneretc.)

Both of these classes have underscore internal prefixes that preserve state. Uses _stateand _ideventemitter _idfor storing event and event handlers for storing state and identifier.

Now, when I create a model using the composition of an object, for example,

var Model = extend({}, Observable, {
    constructor: function () {
        // Oops, I was supposed to know Observable uses the _state name already
        this._state = { ... }
    },
    someMethod: function () { ... }
})

This causes a problem because it is observablealready using an internal property _state, and now a name clash occurs.

I find it ugly to just “know” which objects rely on which internal properties for mixin work safely.

How to avoid mixing in two objects that use the same internal property name?

Ideally, this will be solved using ES6 private names, but we cannot do this yet, and we cannot imitate them without losing performance. If you cannot provide emulation of ES6 names, which does not have a large penalty for performance , I am not interested in these solutions.

bind, . __eventEmitter_events __observable_state. , .

+5
1

- " "

var state = "Model@v0.1.3~state";
var Model = extend({}, Observable, {
    constructor: function () {
        // Nice, I used a namespace and don't clash with "Observable@v0.2.3~state"
        this[state] = { ... }
    },
    someMethod: function () { ... }
})
0

All Articles