Search code examples
javascriptflux

Why to assign prototype to itself


I found an interesting use case of Object.assign in Flux's documentation, example of Dispatcher in its architecture:

var assign = require('object-assign');

var _callbacks = [];

var Dispatcher = function() {};
Dispatcher.prototype = assign({}, Dispatcher.prototype, {
    register: function(callback) {
        _callbacks.push(callback);
        return _callbacks.length - 1; // index
    }
});

Source: http://facebook.github.io/flux/docs/todo-list.html#creating-a-dispatcher

What's the reason of assigning an extended prototype to the same object's prototype?


Solution

  • My guess is that they just wanted to extend prototype. When Object.assign (npm object-assign is a pollyfill) is used like this:

    assign({}, Dispatcher.prototype, {/* ... */});
    

    it returns a new object, result of extension of Dispatcher.prototype (properties from prototype are copied to new object), however original Dispatcher.prototype is not affected. So in order to actually extend it they had to reassign prototype altogether with the new extended object.

    However it would make more sense to avoid confusing assignment:

    assign(Dispatcher.prototype, {/* ... */});
    

    Above would just extend prototype without need of reassignment.