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

标签 javascript underscore.js fabricjs

我创建了一个对象,其中包含一些跨类所需的常用方法:

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 的方法,它调用 getPointByIndex方法来自 PathBased目的。当我的程序调用route.createRoutePoint()时,我收到错误 getPointByIndex未定义。

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

如何正确执行此操作?

最佳答案

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

说明:

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

关于javascript - 下划线扩展方法和fabric.js子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014742/

相关文章:

javascript - Fabricjs。具有圆 Angular 和描边的图像

fabricjs - fabric.js Canvas 监听键盘事件?

javascript - 在 javascript String.replace() 中清理像输入(第二个参数)一样的正则表达式

javascript - 在水平画笔上使用 .filter()

javascript - 在对象数组中搜索匹配的键/值对的快速方法

attributes - 使用下划线的 JAXB 属性

javascript - d3.js scaleTime 返回未定义

javascript - 关于javascript中对象字面量的解释

javascript - UnderscoreJS - 如何使用迭代器之一展平对象?

javascript - 当 Canvas 重新定位时,Fabric.js Canvas 坐标的值会发生变化