JSPM

  • Created
  • Published
  • Downloads 1079
  • Score
    100M100P100Q101102F
  • License Apache-2.0

Clone an ES6 Class as Another Class Name for Isolating Class Static Properties.

Package Exports

  • clone-class

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (clone-class) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

CLONE CLASS

Greenkeeper badge NPM Version Build Status TypeScript

Clone an ES6 Class as Another Class Name for Isolating Class Static Properties.

EXAMPLE

Shell

$ npm i clone-class

TypeScript

import cloneClass from 'clone-class'

class Employee {
  public static company: string

  constructor(
    public name: string,
  ) {
  }

  public info() {
    console.log(`Employee ${this.name}, Company ${(this.constructor as any).company}`)
  }
}

const GoogleEmployee = cloneClass(Employee)
GoogleEmployee.company = 'Google'

const MicrosoftEmployee = cloneClass(Employee)
MicrosoftEmployee.company = 'Microsoft'

const employee1 = new GoogleEmployee('Tom')
const employee2 = new MicrosoftEmployee('Jerry')

employee1.info()
// Output: Employee Tom, Company Google
employee2.info()
// Output: Employee Jerry, Company Microsoft

The most tricky part of this code is (this.constructor as any).company.

It will be very clear after we break down it as the following steps:

  1. this.constructor is the constructor function of the class, which shuold be the class function itself.
  2. company is a static properity defined in Employee class, which will be set as a property on the class function.
  3. So this.constructor.company is equal to Employee.company, except that we will not need to know the exact name of the class, Employee in this case. We use this pattern is because we need to visit the class function even we do not know it's name.

CHANGELOG

v0.4.0 (Apr 2018)

First publish version.

v0.0.1 (Apr 23, 2018)

Initial version, code comes from Project Wechaty.

Learn more about the full story at Chatie blog: New Feature: Multi-Instance Support for Wechaty v0.16(WIP)

SEE ALSO

An UseCase of clone-class can be found on a blog article writen by me from Chatie blog:

It's the place where this module comes from, worth to spent some time to have a look if you are interested.

AUTHOR

Huan LI <zixia@zixia.net>

profile for zixia on Stack Exchange, a network of free, community-driven Q&A sites
  • Code & Docs © 2018 Huan LI <zixia@zixia.net>
  • Code released under the Apache-2.0 License
  • Docs released under Creative Commons