0

Possible Duplicate:
Javascript: Do I need to put this.var for every variable in an object?

I wanted to create a "class" in JavaScript which other "classes" should inherit from.

Thus, I added "public methods" using the prototype object.

Inside these methods, I want to access private properties of my class.

It seems like I cannot access them. How do I do this? This is my code:

<!doctype html>

<html>

    <head>
        <title>OOP test</title>

        <script>

            var ParentClass = function(){
                var data = [];
            }

            ParentClass.prototype.addData = function(somedata){
                data.push(somedata); // ReferenceError: Can't find variable: data
            }

            var p = new ParentClass();
            p.addData("foo");

        </script>
    </head>

    <body>
    </body>

</html>
Community
  • 1
  • 1
Timo Ernst
  • 15,243
  • 23
  • 104
  • 165

3 Answers3

2

<head>
    <title>OOP test</title>

    <script>

        var ParentClass = function(){
            this.data = [];
        }

        ParentClass.prototype.addData = function(somedata){
            this.data.push(somedata); // ReferenceError: Can't find variable: data
        }

        var p = new ParentClass();
        p.addData("foo");

    </script>
</head>

<body>
</body>

Aidamina
  • 1,894
  • 20
  • 14
2

There are no public or private (not even when you quote them), there is just object properties and variables. You cannot access variables that are not in scope. The .addData method is defined out of scope of data variable.

Object properties can be accessed as long as you have a reference to the object, so make it an object property:

var ParentClass = function(){
    this.data = [];
}

ParentClass.prototype.addData = function(somedata){
    this.data.push(somedata);
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • The call of `data.push(somedata);` also needs to be changed to `this.data.push(somedata);` – Timo Ernst Nov 22 '12 at 14:38
  • @valmar yeah thanks, I forgot that in other languages (C#, java, where the OP is most likely coming from) `this` is optional so it would not be obvious – Esailija Nov 22 '12 at 14:40
0

It throws a reference error because the variable 'data' is 'private' to the function 'ParentClass'.. to simulate the functionaility you could use a closure type method.

var ParentClass = function(){
    var data = [];
    this.addData = function(somedata){
        data.push(somedata); // Closure will have access to all variables in 'ParentClass'
    }
}

However this will intefere with the prototypical inheritance you seem to be wishing to implement.

Dpolehonski
  • 948
  • 6
  • 11