javascript - Construct function from strings -
this question has answer here:
i wondering if possible. let's use 'canvas' 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 doesn't work wonder if it's possible dynamically construct functions in way. achive sort of user interface input method name , parameters , executed in specific context (canvasrenderingcontext2d in particular example)
try changing line
this.ctx.method.apply(this.ctx, params);
to
this.ctx[method].apply(this.ctx, params);
since canvas's property ( value function) name stored in variable.
for example, if object is
var obj = { a: function(){console.log(1)} }
you can invoke
obj.a();
or if have
var b = "a"; obj[b]();
Comments
Post a Comment