user2251919
user2251919

Reputation: 675

Canvas object and multiple instances inside another object?

I have a canvas object that I can call like so

var canvas = new Canvas();

The canvas object also has alot of functions in its prototype. The object essentially creates a canvas element, with a few functions such as setWidth, getContext etc.

I have also a Layer object that is essentially a canvas with added functionality. I thought it would be a good idea to set the Layer's prototype to the Canvas. This worked great and everything was good.

The problem starts when I want to use multiple layers, as each layer should have his own canvas. But as the canvas is the Layers prototype, the prototype points to only one canvas element. So when I start using multiple layers, the canvases always get overwritten as the canvas element in the layers prototype points to the same canvas object.

I hope so far I made sense!

I know I could add the canvas to the layer as a property, but then instead of doing,

layer.setWidth(900);

I would have to do

layer.canvas.setWidth(900);

I guess my question is, how can I inherit the Canvas objects functions but on instantiating a new layer get it to create a new canvas element with it?

As requested the 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;

 })();

Upvotes: 4

Views: 439

Answers (1)

flavian
flavian

Reputation: 28511

All you need is:

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

Stop introducing massive overhead with immediately invoked functions and closures and other such things. They are completely useless. keep the code clean. IF you don't 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);

Upvotes: 1

Related Questions