javascript - Canvas object and multiple instances inside another object? -
i have canvas object can call so
var canvas = new canvas();
the canvas object has alot of functions in prototype. object creates canvas element, few functions such setwidth
, getcontext
etc.
i have layer
object canvas added functionality. thought idea set layer
's prototype canvas
. worked great , good.
the problem starts when want use multiple layers, each layer should have own canvas. canvas layers prototype, prototype points 1 canvas element. when start using multiple layers, canvases overwritten canvas element in layers prototype points same canvas object.
i hope far made sense!
i know add canvas layer property, instead of doing,
layer.setwidth(900);
i have do
layer.canvas.setwidth(900);
i guess question is, how can inherit canvas
objects functions on instantiating new layer create new canvas element it?
as requested code (simplified)
var carl = {}; carl.canvas = (function() { "use strict"; function canvas(config) { this._init(config); }; canvas.prototype._init = function(config) { this.element = document.createelement("canvas"); this.context = this.element.getcontext("2d"); }; canvas.prototype.setwidth = function(width) { this.element.width = width; }; canvas.prototype.getwidth = function() { return this.element.width; }; canvas.prototype.setheight = function(height) { this.element.width = height; }; canvas.prototype.getheight = function() { return this.element.height; }; canvas.prototype.getcontext = function() { return this.context; }; return canvas; }}(); carl.layer = (function() { "use strict"; function layer() { }; layer.prototype = new carl.canvas(); return layer; })();
all need is:
carl.layer = function() { carl.canvas.call(this); }; carl.layer.prototype = object.create(carl.canvas.prototype);
stop introducing massive overhead invoked functions , closures , other such things. useless. keep code clean. if don't want object.create
, can use polyfill it.
function inherits(child, parent) { function temp() {}; temp.prototype = parent.prototype; child.prototype = new temp(); child.prototype.constructor = child; }; carl.layer = function() { carl.canvas.call(this); }; inherits(carl.layer, carl.canvas);
Comments
Post a Comment