Is it possible to give javascript partial class behavior like C# or monkey patching like Ruby does?

前端 未结 5 1817
感动是毒
感动是毒 2021-01-01 05:14

The idea behind partial classes is that you can group certain functions together. The best example of this in C# is putting control definitions in one file and the event han

5条回答
  •  没有蜡笔的小新
    2021-01-01 06:13

    Here is one approach using ES6 and compatible with ES5 using Babel:

    In this example I create a MyClass in several files, using three files:

    index.js (this is important so you can import the class just via the folder name)

    symbols.js (this contains the symbols for private members)

    additionalMethods.js (a file that is later attached to the class prototype)

    index.js content

    import symbols from "./symbols";
    
    export default class MyClass {
      [symbols.existentPrivateMethod]() {
        return "this is the result";
      }
    }
    
    import additionalMethod, {anotherAdditionalMethod, additionalPrivateMethod} from "./additionalMethods";
    const additionalMethodsObject = {
      additionalMethod: additionalMethod,
      anotherAdditionalMethod: anotherAdditionalMethod
    };
    additionalMethodsObject[symbols.additionalPrivateMethod] = additionalPrivateMethod;
    
    Object.assign(MyClass.prototype, additionalMethodsObject);
    

    additionalMethods.js contents

    import symbols from "./symbols";
    
    export default function additionalMethod() {
      return this[symbols.existentPrivateMethod]();
    }
    
    export function anotherAdditionalMethod() {
      return this[symbols.additionalPrivateMethod]();
    }
    
    export function additionalPrivateMethod() {
      return "yet another result";
    }
    

    symbols.js content

    const symbols = {
      existentPrivateMethod: Symbol("myPrivateMethod"),
      additionalPrivateMethod: Symbol("additionalPrivateMethod")
    };
    
    export default symbols;
    

    Complete project https://github.com/nicosommi/partialClass

    Complete explanation https://nicosommi.com/2015/08/10/partial-class-approach-for-es6/

提交回复
热议问题