Wrap all methods / properties on an embedded object

I would like to create an object that I can pass in place of an inline object (in particular, an instance CanvasRenderingContext2D). I would like most methods to forward built-in equivalents, but I would also like to add some of my methods and wrap some of the built-in modules.

Here is what I came up with:

function MyContext(ctx) {
  for (var k in ctx) {
    (function(k) {
      if (typeof(ctx[k]) == 'function') {
        this[k] =  ctx[k].bind(ctx);
      } else {
        Object.defineProperty(this, k, {
          get: function() { return ctx[k]; },
          set: function(x) { ctx[k] = x; }
        });
      }
    }).bind(this)(k);
  }

  this.stroke = function() {
    console.log('called stroke');
    ctx.stroke();
  };
}

Object A MyContextcan be used just like inline CanvasRenderingContext2D:

var canvas = document.querySelector('canvas'),
    ctx = canvas.getContext('2d');

var mtx = new MyContext(ctx);
mtx.beginPath();
mtx.moveTo(100, 50);
mtx.lineTo(200, 50);
mtx.lineTo(200, 75);
mtx.closePath();
mtx.strokeStyle = 'red';
mtx.stroke();

except that the call logs stroke.

Is this the best way to achieve this? Is it possible to do this more efficiently using a prototype?

+4
source share

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


All Articles