0

I was wondering if something like this is possible. Let's use 'canvas' for example:

(function(){
function Canvas(canvas){
  this.canvas = document.querySelector('#canvas');
  this.ctx = this.canvas.getContext('2d');
  this.testMethod('fillRect',[10,10,10,10]);
}
Canvas.prototype.testMethod = function(method,params){
this.method = method;
this.params = params;

this.ctx.method.apply(this.ctx, params);

}
var canvas = new Canvas();
})()
<canvas id='canvas' width=400 height=400></canvas>

Of course it doesn't work but I wonder if it's possible to dynamically construct functions in this way. What I would like to achive is sort of user interface where I would input method name and parameters and they would be executed in specific context (CanvasRenderingContext2D in this particular example)

przemoo83
  • 315
  • 1
  • 3
  • 13

1 Answers1

1

try changing this line

this.ctx.method.apply(this.ctx, params);

to

this.ctx[method].apply(this.ctx, params);

since canvas's property ( whose value is a function) name is stored in a variable.

for example, if your object is

var obj = {
 a: function(){console.log(1)}
}

you can invoke

obj.a(); 

or if you have

var b = "a";
obj[b]();
gurvinder372
  • 66,980
  • 10
  • 72
  • 94