mix.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module utils/mix
  7. */
  8. /**
  9. * Copies enumerable properties and symbols from the objects given as 2nd+ parameters to the
  10. * prototype of first object (a constructor).
  11. *
  12. * class Editor {
  13. * ...
  14. * }
  15. *
  16. * const SomeMixin = {
  17. * a() {
  18. * return 'a';
  19. * }
  20. * };
  21. *
  22. * mix( Editor, SomeMixin, ... );
  23. *
  24. * new Editor().a(); // -> 'a'
  25. *
  26. * Note: Properties which already exist in the base class will not be overriden.
  27. *
  28. * @param {Function} [baseClass] Class which prototype will be extended.
  29. * @param {Object} [...mixins] Objects from which to get properties.
  30. */
  31. export default function mix( baseClass, ...mixins ) {
  32. mixins.forEach( mixin => {
  33. Object.getOwnPropertyNames( mixin ).concat( Object.getOwnPropertySymbols( mixin ) )
  34. .forEach( key => {
  35. if ( key in baseClass.prototype ) {
  36. return;
  37. }
  38. const sourceDescriptor = Object.getOwnPropertyDescriptor( mixin, key );
  39. sourceDescriptor.enumerable = false;
  40. Object.defineProperty( baseClass.prototype, key, sourceDescriptor );
  41. } );
  42. } );
  43. }