Advertisement
Guest User

Untitled

a guest
Jan 31st, 2015
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. var emptyFunction = () => {}
  2.  
  3. /**
  4. * creates a new constructor function with `objects` merged in its prototype.
  5. * to prevent unwanted errors when calling `super()` a child class, the
  6. * prototype is actually a proxy returning **or** the actual method, or an
  7. * empty function.
  8. *
  9. * as the proxy gets the same shape as the initial object, the prototype chain
  10. * actually receives the present methods.
  11. *
  12. * @param {Object} ...objects
  13. * @returns {Function}
  14. */
  15. function mixins(...objects) {
  16. var proto = {}
  17. objects.forEach((object) => {
  18. if(object == null || object === false) {
  19. return
  20. }
  21. for(let methodName in object) {
  22. let previousMethod = proto[methodName]
  23. let method = object[methodName]
  24. let actualMethod = method
  25. if(previousMethod) {
  26. // if mixins have multiple methods, we merge them
  27. actualMethod = function(...args){
  28. previousMethod.apply(this, args)
  29. method.apply(this, args)
  30. }
  31. }
  32. proto[methodName] = actualMethod
  33. }
  34. })
  35. function ComposedClass(){
  36. ComposedClass.prototype.constructor.apply(this, arguments)
  37. }
  38. ComposedClass.prototype = new Proxy(proto, {
  39. get(object, methodName) {
  40. return proto[methodName] || emptyFunction
  41. },
  42. set() {
  43. throw new TypeError()
  44. }
  45. })
  46. return ComposedClass
  47. }
  48.  
  49. const A = {
  50. constructor() {
  51. this.name = "defaultName"
  52. },
  53. getName() {
  54. return this.name
  55. },
  56. setName(name) {
  57. this.name = name
  58. }
  59. }
  60.  
  61. const B = {
  62. constructor() {
  63. this.foo = "bar"
  64. }
  65. }
  66.  
  67. class Test extends mixins(A, B) {
  68. constructor() {
  69. super()
  70. }
  71. test() {
  72. super() // doesn't throw, as the proxy returns an empty function
  73. return "foo"
  74. }
  75. }
  76.  
  77. const t = new Test()
  78.  
  79. console.log(t.name)
  80. console.log(t.foo)
  81. console.log(t.test())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement