2014-09-26 64 views
0

为什么不能在draw()函数中访问Ball对象私有成员?当我登录它们时,私有变量变得不确定。不应该有特权的方法能够访问私人成员?从特权方法访问私有成员

var ctx; 

(function() { 
    console.log("Hello world!"); 

    var canvas = document.getElementById('gameCanvas'); 
    ctx = canvas.getContext("2d"); 

    var ball1 = new Ball(); 
    ball1.draw(); 

})(); 

function Ball() { 
    var that = this; // for private methods 

    var posY  = 50; 
    var posX  = 50; 
    var velocityX = 0; 
    var velocityY = 0; 
    var radius = 10; 

    this.draw = function() { 
     console.log(this.posY); // outputs 'undefined' 
     ctx.beginPath(); 
     ctx.fillStyle = '#444'; 
     ctx.arc(this.posX, this.posY, this.r, 0, Math.PI*2); 
     ctx.fill(); 
    } 
} 
+0

它们是局部变量,不是对象的一部分。把''这个''放在'console.log(posY);' – epascarello 2014-09-26 12:57:05

回答

2

当你与var定义他们,让他们“私人”,他们不会是在this范围。丢掉this只是引用变量,它会工作。

var ctx; 

(function() { 
    console.log("Hello world!"); 

    var canvas = document.getElementById('gameCanvas'); 
    ctx = canvas.getContext("2d"); 

    var ball1 = new Ball(); 
    ball1.draw(); 

})(); 

function Ball() { 
    var that = this; // for private methods 

    var posY  = 50; 
    var posX  = 50; 
    var velocityX = 0; 
    var velocityY = 0; 
    var radius = 10; 

    this.draw = function() { 
     console.log(posY); 
     ctx.beginPath(); 
     ctx.fillStyle = '#444'; 
     ctx.arc(posX, posY, r, 0, Math.PI*2); 
     ctx.fill(); 
    } 
} 
+0

哦谢谢!但是这种方法可能会带来什么问题(引用错误的东西)?例如,如果我从param创建了多个球,那么这个球就可以吗? – tobbe 2014-09-26 13:21:02

0

this.需要我相信:

this.posY  = 50; 
this.posX  = 50; 
this.velocityX = 0; 
this.velocityY = 0; 
this.radius = 10; 

(不var