2014-09-26 51 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