- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 344字
- 2021-07-09 19:07:38
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.
- Unity 2020 By Example
- 跟“龍哥”學(xué)C語言編程
- 程序員數(shù)學(xué):用Python學(xué)透線性代數(shù)和微積分
- 人臉識別原理及算法:動態(tài)人臉識別系統(tǒng)研究
- SEO實(shí)戰(zhàn)密碼
- Java Web開發(fā)技術(shù)教程
- Quarkus實(shí)踐指南:構(gòu)建新一代的Kubernetes原生Java微服務(wù)
- Python編程與幾何圖形
- Protocol-Oriented Programming with Swift
- 深度學(xué)習(xí):Java語言實(shí)現(xiàn)
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- Processing創(chuàng)意編程指南
- Unity&VR游戲美術(shù)設(shè)計實(shí)戰(zhàn)
- 創(chuàng)意UI Photoshop玩轉(zhuǎn)移動UI設(shè)計
- Python預(yù)測分析實(shí)戰(zhàn)