将构造函数添加到注入的Project类中

时间:2019-02-18 14:57:38

标签: javascript paperjs

我正在尝试向Project添加一个称为ctor的构造函数,以便在实例化它时可以为其添加一些属性。

这是我在Item上使用的(绝对可怕的)技巧:

const canvas = document.querySelector('canvas')
paper.setup(canvas)

paper.Item.inject({
  ctor: function(args) {
    console.log('Item constructed!')
  }
})

// All Items are supposed to call `_initialize` so we "hook" there.
const Item_initialize = paper.Item.prototype._initialize
const Item_ctor = paper.Item.prototype.ctor

paper.Item.prototype._initialize = function(...args) {
  const initializer = Item_initialize.apply(this, args)
  if (Item_ctor) Item_ctor.apply(this)

  return initializer
}

const path = new paper.Path.Line({
  strokeColor: 'black',
  strokeWidth: 5,
  from: 100,
  to: 50
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-core.js"></script>
<canvas></canvas>

不幸的是,以上技巧不适用于Project

const canvas = document.querySelector('canvas')
paper.setup(canvas)

paper.Project.inject({
  ctor: function(args) {
    // Not called
    console.log('Project constructed!')
  }
})

const Project_initialize = paper.Project.prototype._initialize
const Project_ctor = paper.Project.prototype.ctor

paper.Project.prototype._initialize = function(...args) {
  const initializer = Project_initialize.apply(this, args)
  if (Project_ctor) Project_ctor.apply(this)

  return initializer
}

const project = new paper.Project(canvas)
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-core.js"></script>
<canvas></canvas>

我在这里想念什么?

0 个答案:

没有答案