[英]How does the inheritance model of KineticJS work?
我是JavaScript的新手,我知道可以使用不同的繼承模型。 我有一個項目,我使用了KineticJS,我在他們的更新日志中注意到他們使用項目的v3.10.3版本更改了繼承模型,這樣我們就可以'more easily extend or add custom methods to Kinetic classes'
我已經做了一些搜索,但我似乎無法在任何地方找到一個明確的例子。 我想知道是否有人能告訴我將屬性和方法添加到Kinetic類的正確方法是什么,以及我如何擴展它們來創建我自己的自定義類? 在KavascriptJS中使用的繼承模型是javascript中的常見模型嗎?
您可以使用不同的方式。
1 Kineticjs的方式。 來自kineticjs來源的例子:
Kinetic.Circle = function(config) {
this._initCircle(config);
};
Kinetic.Circle.prototype = {
_initCircle: function(config) {
this.createAttrs();
// call super constructor
Kinetic.Shape.call(this, config);
this.shapeType = 'Circle';
this._setDrawFuncs();
},
drawFunc: function(canvas) {
/*some code*/
}
/* more methods*/
};
Kinetic.Global.extend(Kinetic.Circle, Kinetic.Shape);
2你也可以用coffeescript繼承它: coffeescript Class但是在js中看起來不太好:
var Gallery,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Gallery = (function(_super) {
__extends(Gallery, _super);
function Gallery(config) {
Kinetic.Stage.call(this, config);
}
Gallery.prototype.add = function(item) {
console.log(item);
return Gallery.__super__.add.call(this, item);
};
Gallery.prototype.method = function() {
return console.log('test');
};
return Gallery;
})(Kinetic.Stage);
我建議遵循在KineticJS源中完成的方法。 這篇博客文章解釋了如何但有點過時,所以我將包含一個最新的示例,該示例還說明了如何向自定義形狀添加屬性。
下面的代碼顯示了創建一個新的Shape.Arc
對象的示例。 此示例顯示如何添加新功能和屬性。
var Shape = {};
(function () {
Shape.Arc = function (config) {
this.initArc(config);
};
Shape.Arc.prototype = {
initArc: function (config) {
Kinetic.Shape.call(this, config);
this._setDrawFuncs();
this.shapeType = 'Arc;'
drc.ui.utils.setupShape(this);
},
drawFunc: function (context) {
context.beginPath();
context.arc(0,0, this.getRadius(), this.getStartAngle(),
this.getEndAngle(), true);
context.fillStrokeShape(this);
}
};
Kinetic.Util.extend(Shape.Arc, Kinetic.Shape);
//Add properties to shape.
//The code below adds the getRadius(), getStartAngle() functions above.
Kinetic.Factory.addGetterSetter(Shape.Arc, 'radius', 0);
Kinetic.Factory.addGetterSetter(Shape.Arc, 'startAngle', 0);
Kinetic.Factory.addGetterSetter(Shape.Arc, 'endAngle', 180);
})();
將它包裝在匿名函數中非常重要,因此可以創建多個實例。
要創建弧:
var arc = new Shape.Arc({
radius: radius,
x: centreX,
y: centreY,
startAngle: 0,
endAngle: Math.PI * 2
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.