下划线扩展方法和 fabric.js 子类

Underscore extend method and fabric.js subclass

我创建了一个对象,其中包含我在 类:

中需要的一些常用方法
var PathBased = {
    appendPoint: function(point) {
            var lastPointIndex = this.getLastPointIndex();
            this.addPointAfterIndex(point, lastPointIndex);
    },

    getPointByIndex: function(index) {
            var pointX, pointY;

            if (index == 0) {
                    pointX = this.path[index][1];
                    pointY = this.path[index][2];
            } else {
                    pointX = this.path[index][3],
                    pointY = this.path[index][4];
            }

            return new fabric.Point(pointX, pointY);
    },

    ...

};

然后我想创建一个包含此功能的结构子类。我使用以下代码执行此操作:

var Route = _.extend(fabric.util.createClass(fabric.Path, {
    initialize: function(path, options) {
        var options = options || {};
        this.app = options.app;
        this.model = options.model;

        options.stroke = options.stroke || this.app.config.routeStroke;
        options.fill = options.fill || this.app.config.routeFill;

        this.callSuper('initialize', path, options);

        _.bindAll(this, 'handleMoving');
        this.on('moving', this.handleMoving);
    },

    createRoutePoint: function(pointIndex) {
        var point = this.getPointByIndex(pointIndex);

        return new RoutePoint({
                top: point.y,
                left: point.x,
                pointIndex: pointIndex,
                route: this,
                app: this.app,
                model: this.model
        });
    },

        ...

}), PathBased);

页面加载后,在 Javascript 控制台中,我可以看到如果我创建一个新的 Route 对象:var route = new Route,该对象实际上具有来自PathBased 对象。例如,我可以看到 route.getPointByIndex 存在。

但是,正如您在上面看到的,Route 对象有一个名为 createRoutePoint 的方法,它从 PathBased 对象调用 getPointByIndex 方法。当我的程序调用 route.createRoutePoint() 时,出现 getPointByIndex 未定义的错误。

我这里的extend方法是不是用错了?似乎存在某种范围问题,导致 getPointByIndex 方法在 Route 对象的上下文中不可用。

如何正确执行此操作?

var Route = fabric.util.createClass(fabric.Path, {
    ...
});
_.extend(Route.prototype, PathBased);

说明:

Route 是一个构造函数,因此尽管它可以具有属性,但这些属性不会被您使用它创建的 Route 实例继承。这些对象以 Route.prototype 作为原型,因此添加到 Route.prototype 的任何属性都由实例继承。