如何在JavaScript(ES6)中继承Selection对象?

时间:2017-09-22 22:23:08

标签: javascript google-chrome ecmascript-6 es6-class

我想做以下事情:

class MySelection extends Selection {
   constructor() {
       super()
   }
   someNewMethod1() {

   }
   someNewMethod2() {

   }
}

但是,我目前仅限于执行const instance = document.getSelection(),然后手动添加静态方法。这样做是没有问题的,但我只是好奇是否有一种方法可以为Selection对象使用类语法 - 毕竟,它是大写的,所以你这样做了期望能够使用new Selection()实例化它或将其子类化。

1 个答案:

答案 0 :(得分:0)

我实际上实现了这一点,它对我来说很好,这里是我的代码示例

从'时刻'导入时刻 从'lodash'

导入_
class Model {
  constructor(props) {
    this.initialize(props)
  }

  initialize(props) {
    this.id = props.id && Number(props.id) || null
    this.createdAt = props.createdAt && moment(props.createdAt) || null
    this.updatedAt = props.updatedAt && moment(props.updatedAt) || null
    this.deletedAt = props.deletedAt && moment(props.deletedAt) || null
  }

  toJson() {
    const props = Object.assign({}, this)

    _.forOwn(props, (value, key) => {
      if (value instanceof moment) {
        props[key] = value.format('YYYY-MM-DD HH:mm:ss')
      }
    })
    return props
  }
}

import moment from 'moment'
import Model from './Model'
import User from './User'

class Article extends Model {
  constructor(props) {
    super(props)

    this.initialize(props)
  }

  initialize(props) {
    super.initialize(props)

    this.slug = props.slug | ''
    this.title = props.title || ''
    this.description = props.description || ''
    this.content = props.content || ''
    this.published = props.published || false
    this.publishedAt = props.publishedAt ? moment(props.publishedAt) : null

    // relate user model
    this.user = props.user ? new User(props.user) : null
  }
}

export default Article

我可以轻松启动Article或Model类,并使用实例或静态函数,如

const Article = new Article({ // });

Article.toJson();