动态添加构造函数

时间:2018-02-04 05:02:15

标签: javascript

有没有办法动态地将构造函数添加到Class 而不用更改原始类本身?

我正在使用一个库来实例化对象:

var path = new Path()

我想做的是这样的事情:

// obviously won't work but you get the point
Path.prototype.constructor = function() {
  console.log(this, 'was created')
}

var path = new Path()

我显然可以使用Factory来创建我的对象,在该Factory中我可以添加自定义函数并触发它。这是行不通的,因为我正在使用的库不会在内部使用该工厂。

1 个答案:

答案 0 :(得分:1)

是的,您可以,但变量Path必须为非const才能生效。这种方法要求您仍然可以调用原始constructor

Path = class extends Path {
  constructor () {
    super()
    console.log(this, 'was created')
  }
}

class Path {
  constructor () {
    console.log('old constructor')
  }
  
  foo () {
    console.log('bar')
  }
}

Path = class extends Path {
  constructor () {
    super()
    console.log(this, 'was created')
  }
}

let path = new Path()
path.foo()

除了Path之外,您还可以将constructor替换为与原始类相同的新类:

Path = (Path => {
  return Object.setPrototypeOf(
    Object.setOwnPropertyDescriptors(function () {
      console.log(this, 'was created')
    }, Object.getOwnPropertyDescriptors(Path)),
    Object.getPrototypeOf(Path)
  )
})(Path)

class Path {
  constructor () {
    console.log('old constructor')
  }

  foo () {
    console.log('bar')
  }
}

Path = (Path => {
  return Object.setPrototypeOf(
    Object.defineProperties(function () {
      console.log(this, 'was created')
    }, Object.getOwnPropertyDescriptors(Path)),
    Object.getPrototypeOf(Path)
  )
})(Path)

let path = new Path()
path.foo()