Canvas object and multiple instances inside another object?

I have a canvas object that I can call it that

var canvas = new Canvas(); 

The canvas object also has many features in its prototype. An object essentially creates a canvas element with several functions, such as setWidth , getContext , etc.

I also have a Layer object, which is essentially a canvas with added functionality. I thought it would be nice to install a Layer prototype for Canvas . It worked great and everything was fine.

The problem starts when I want to use several layers, since each layer should have its own canvas. But since the canvas is a Layers prototype, the prototype points to only one canvas element. Therefore, when I start using multiple layers, canvases are always overwritten, since the canvas element in layer prototypes points to the same canvas object.

Hope so far I made sense!

I know that I could add canvas to the layer as a property, but instead

 layer.setWidth(900); 

I would have to do

 layer.canvas.setWidth(900); 

I assume my question is how can I inherit the functions of Canvas objects, but when creating a new layer, create it using the new canvas element?

As per code request (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; })(); 
+4
source share
1 answer

All you need is:

 carl.Layer = function() { carl.Canvas.call(this); }; carl.Layer.prototype = Object.create(carl.Canvas.prototype); 

Stop entering massive overheads with immediately invoked functions and closures and other similar things. They are completely useless. keep the code clean. If you do not want Object.create , you can use polyfill for 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); 
+1
source

Source: https://habr.com/ru/post/1480692/


All Articles