我创建了一个对象,其中包含一些跨类所需的常用方法:
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/