官术网_书友最值得收藏!

The mixin pattern

Mixins help in significantly reducing functional repetition in our code and help in function reuse. We can move this shared functionality to a mixin and reduce duplication of shared behavior. You can then focus on building the actual functionality and not keep repeating the shared behavior. Let's consider the following example. We want to create a custom logger that can be used by any object instance. The logger will become a functionality shared across objects that want to use/extend the mixin:

var _ = require('underscore');
//Shared functionality encapsulated into a CustomLogger
var logger = (function () {
  var CustomLogger = {
    log: function (message) {
      console.log(message);
    }
  };
  return CustomLogger;
}());

//An object that will need the custom logger to log system specific logs
var Server = (function (Logger) {
  var CustomServer = function () {
    this.init = function () {
      this.log("Initializing Server...");
    };
  };

  // This copies/extends the members of the 'CustomLogger' into 'CustomServer'
  _.extend(CustomServer.prototype, Logger);
  return CustomServer;
}(logger));

(new Server()).init(); //Initializing Server...

In this example, we are using _.extend from Underscore.js—we discussed this function in the previous chapter. This function is used to copy all the properties from the source (Logger) to the destination (CustomServer.prototype). As you can observe in this example, we are creating a shared CustomLogger object that is intended to be used by any object instance needing its functionality. One such object is CustomServer—in its init() method, we call this custom logger's log() method. This method is available to CustomServer because we are extending CustomLogger via Underscore's extend(). We are dynamically adding functionality of a mixin to the consumer object. It is important to understand the distinction between mixins and inheritance. When you have shared functionality across multiple objects and class hierarchies, you can use mixins. If you have shared functionality along a single class hierarchy, you can use inheritance. In prototypical inheritance, when you inherit from a prototype, any change to the prototype affects everything that inherits the prototype. If you do not want this to happen, you can use mixins.

主站蜘蛛池模板: 汤阴县| 永宁县| 三明市| 锡林郭勒盟| 蛟河市| 枣强县| 潼关县| 凤山市| 贞丰县| 嘉鱼县| 吉林省| 丹凤县| 萍乡市| 阜康市| 微山县| 汪清县| 苍溪县| 江源县| 镇巴县| 长子县| 蒙自县| 沙河市| 广丰县| 沙田区| 丹阳市| 抚州市| 德安县| 阿拉尔市| 余干县| 海口市| 镇雄县| 西青区| 香河县| 辉南县| 青海省| 久治县| 同心县| 澄江县| 沐川县| 即墨市| 乌拉特中旗|