html5 - Assigning value of 'this' in JavaScript constructor -
i'm learning javascript , i'm playing html5 canvas api. since first have create canvas element, , 2d/3d context (which 2 unconnected variables) seemed logical create merge 2 one.
idea have graphics (gfx
) object (which context object) , graphics.canvas
reference canvas element can gfx.fillrect(0,0,150,75);
, maybe re size canvas gfx.canvas.width = x;
etc...
when try create constructor function, doesn't work out, have come solution return context
object canvas
property i'm not sure if right way.
what best approach problem?
here's code:
function canvas (context, width, height) { var canvas = document.createelement('canvas'), contex = canvas.getcontext(context); = contex; // <<-- getting error here this.canvas = canvas; this.canvas.width = width; this.canvas.height = height; this.append = function () { document.body.appendchild(this.canvas); }; } function canvas2 (context, width, height) { var canvas = document.createelement('canvas'), contex = canvas.getcontext(context); contex.canvas = canvas; contex.canvas.width = width; contex.canvas.height = height; contex.append = function () { document.body.appendchild(this.canvas); }; return contex; } var gfx = new canvas('2d', 400, 400), gfx2 = canvas2('2d', 400, 400); gfx.append(); gfx2.append();
this
reserved word in javascript , refers read-only context variable. cannot reassign it.
if there no reason can't continue use contex
variable, that. if need create local variable, name else:
var = contex;
Comments
Post a Comment