为什么我无法在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 :(得分:2)
当您使用var
定义它们,因此它们是"私有" 时,它们不会出现在this
范围< / em>的。删除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();
}
}
答案 1 :(得分:0)
this.
:
this.posY = 50;
this.posX = 50;
this.velocityX = 0;
this.velocityY = 0;
this.radius = 10;
(不含var
)