如何扩展PaperJS静态构造器?解决Shape.Rectangle继承实例异常问题
问题根源
paper.Shape.Rectangle不是可继承的构造函数,它是一个静态工厂方法——调用它会在内部创建并返回一个paper.Shape实例,而非作为构造函数供new操作使用。
你写的代码里,当执行new Rect()时:
- 调用
super(...arguments)本质是调用paper.Shape.Rectangle(),返回一个Shape实例 - JavaScript构造函数如果返回了对象,
new操作会直接返回这个对象,而非Rect类的this - 最终变量
A是Shape实例,自然没有customMethod
解决方案
方案1:继承paper.Shape类,自行实现矩形初始化
直接继承基础的Shape类,在构造函数里完成矩形的路径初始化,这样创建的实例就是你的子类实例,能拥有自定义方法:
class Rect extends paper.Shape { constructor(...args) { super(); // 用PaperJS的Path.Rectangle生成矩形路径,赋值给Shape的path属性 this.path = new paper.Path.Rectangle(...args); } customMethod() { console.log('执行自定义矩形方法'); // 可添加特定于矩形的逻辑,比如计算对角线 const rect = this.path.bounds; console.log(`矩形对角线长度:${Math.sqrt(rect.width**2 + rect.height**2)}`); } } // 使用示例 const myRect = new Rect(50, 50, 200, 150); // 参数支持x,y,width,height或Rectangle对象 myRect.customMethod(); // 正常调用自定义方法
方案2:包装工厂方法,给实例注入自定义方法
如果不想继承Shape,可以直接包装Shape.Rectangle的调用,给返回的Shape实例添加自定义方法:
// 定义自定义方法集合 const RectExtensions = { customMethod() { console.log('自定义方法执行'); }, getArea() { return this.bounds.width * this.bounds.height; } }; // 封装创建矩形的函数 function createRect(...args) { const shape = paper.Shape.Rectangle(...args); // 把自定义方法混入到实例中 Object.assign(shape, RectExtensions); return shape; } // 使用示例 const myRect = createRect(new paper.Rectangle(10, 10, 100, 100)); myRect.customMethod(); // 调用自定义方法 console.log(myRect.getArea()); // 调用新增的计算面积方法
内容的提问来源于stack exchange,提问作者Manu Soman
相关产品推荐
相关产品推荐

