我是oop概念的新手,所以请帮帮我, 每当我使用对象变量时,存储在其中的值都是未定义的。 请检查以下代码
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);
答案 0 :(得分:1)
使用this
代替var
。使用var
创建一个可在function scope
中访问的范围变量,this
将变量附加到当前上下文。请参阅前缀为x, y, r
的{{1}}。
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);
答案 1 :(得分:0)
您无法访问变量x,直到您使用My CustomAuthorizationPolicy.Evaluate() method never fires将其添加为bubble的属性,以访问外部的x。在您的示例中,x是私有变量,您无法访问它
function Bubble(q,w,e)
{
this.x= q;
this.y= w;
this.r = e;
this.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);