【问题标题】:Object variable is undefined对象变量未定义
【发布时间】:2017-08-21 06:00:30
【问题描述】:

我是 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);    

【问题讨论】:

  • 请更具体一点——哪个变量的哪个属性是未定义的?
  • 明确说明您的问题..

标签: javascript oop html5-canvas


【解决方案1】:

使用this 代替var。使用var,您可以创建一个可在function scope 中访问的作用域变量,使用this,您可以将变量附加到当前上下文。请参阅带有前缀this.x, y, r

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>

【讨论】:

    【解决方案2】:

    在将变量 x 添加为气泡的属性之前,您无法访问变量 x 尝试使用 this 来访问外部的 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); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      相关资源
      最近更新 更多