Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从特权方法访问私有成员_Javascript - Fatal编程技术网

Javascript 从特权方法访问私有成员

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

为什么我不能在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();
    }
}

这是需要的。
我相信:

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的球?