Javascript 从特权方法访问私有成员
为什么我不能在draw()函数中访问Ball对象私有成员?当我记录它们时,私有变量没有定义。特权方法不应该能够访问私有成员吗Javascript 从特权方法访问私有成员,javascript,Javascript,为什么我不能在draw()函数中访问Ball对象私有成员?当我记录它们时,私有变量没有定义。特权方法不应该能够访问私有成员吗 var ctx; (function () { console.log("Hello world!"); var canvas = document.getElementById('gameCanvas'); ctx = canvas.getContext("2d"); var ball1 = new Ball(); 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();
}
}
这是需要的。
我相信:
this.posY = 50;
this.posX = 50;
this.velocityX = 0;
this.velocityY = 0;
this.radius = 10;
(没有
var
)当您用var
定义它们时,它们是“私有的”,它们将不在这个范围内。放下这个
,只要引用变量就可以了
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();
}
}
它们是局部变量,不是对象的一部分。放下这个
,它将成为console.log(posY)代码>哦,谢谢!但是这种方法会有任何问题(参考错误)吗?对于ex,如果我从一个参数创建多个带有ex posY的球?