javascript - Object variable is undefined -
i new oop concepts please me out here, whenever using object variable value stored in undefined. please check below code
function bubble(q, w, e) { var x= q; var y= w; var r = e; var canvas= document.getelementbyid('mycanvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(x,y,r,0,2*math.pi); ctx.stroke(); } var b1 = new bubble(100,100,50); var b2 = new bubble(160,160,30); alert(b1.x);
use this instead of var. var create scoped variable accessible in function scope, this attach variable current context. refer x, y, r prefix this..
function bubble(q,w,e) { this.x = q; this.y = w; this.r = e; var canvas = document.getelementbyid('mycanvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(this.x, this.y, this.r, 0, 2*math.pi); ctx.stroke(); } var b1 = new bubble(100,100,50); var b2 = new bubble(160,160,30); alert(b1.x); <canvas id="mycanvas"></canvas>
Comments
Post a Comment