从特权方法访问私有成员

时间:2014-09-26 12:49:43

标签: javascript

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

2 个答案:

答案 0 :(得分:2)

当您使用var定义它们,因此它们是&#34;私有&#34; 时,它们不会出现在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