samuraiseoul
samuraiseoul

Reputation: 2967

Javascript private variable doesn't work unless set to null first

I have a simple Javascript class that I'm trying to make, and it was going great until I encountered a problem that doesn't seem like it should be happening. I have a the following class:

function circle(paper) {
        var x = null;
        var y = null;
        var r = null;

        var x1 = null;
        var y1 = null;
        var R = 0;
        this.G = 0;
        this.B = 0;
        this.lineSize = 1;

        this.paper = paper;

        var that = this;
        this.set = function(x,y,r){
            that.x = x;
            that.y = y;
            that.r = r;
        }

        this.colorOut = function(){
              console.log("R: "+that.R+" G: "+this.G+" B: "+this.B);
        }
}

Now then, R is getting undefined no matter what I do, but if I do var R = null; and in set I do that.R = 0; suddenly it's defined. However from what I found on crockford's site which many SO posts link to for these issues, it seems like he's doing what I'm doing and it's working. as seen in the following code:

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}

Now then, is there something I"m not understanding here, or misinterpretting? I'm new to how classes in JS work, I'm more used the the Java/C++ classes. Anyways, if you need more information just ask! Thanks a lot!

Upvotes: 1

Views: 117

Answers (1)

Pointy
Pointy

Reputation: 413757

There's a big difference between

var R;

and

this.R = something;

The first one is a local variable declaration. It does not add a property to any object. The variable will be visible inside any of those functions you associate with properties of the object, because the functions are created inside that constructor. The variable "R" is part of the closure formed when the functions are instantiated.

The second one establishes a property called "R" on the object under construction.

edit — further clarification:

    this.colorOut = function(){
          console.log("R: "+that.R+" G: "+this.G+" B: "+this.B);
    }

In that function, you refer to "R" as a property of the constructed object; that's what that.R means. When all you've got is that var R; declaration, there is no such property on the object. There is, however a local variable, so you could change the function:

    this.colorOut = function(){
          console.log("R: " + R + " G: "+this.G+" B: "+this.B);
    }

and you'd see the value of the local variable "R", whatever it might be. (If you don't initialize it, then it'll be undefined anyway.)

Upvotes: 5

Related Questions