0

I am new to JS. I am learning JS OOP's concepts. I am trying to use constructor to create private variables in JS. But when I try to access the values using getters, I get an error 'TypeError: 'undefined' is not a function '

function Card(n,s) {
    var number = n;
    var suit = s;
    //getters
    var getNumber = function(){
            return this.number;
    };
    var getSuit = function(){
            return this.suit;
    };
}
var test = new Card(10, 1);
test.getNumber();

I am not able to figure out what the error might be. Need some help on this.

Hozefa
  • 1,676
  • 6
  • 22
  • 34
  • 1
    `var` declares a variable in function scope. Recommended reading: http://stackoverflow.com/q/387707/ – Matt Ball Apr 09 '13 at 03:33
  • 1
    You should prefer prototype based inheritance over what you have now, since it's more memory efficient – zerkms Apr 09 '13 at 03:35

3 Answers3

2

Because you did not attach the functions to this, which points to the instance of the constructor. Properties and functions attached to this are like your "public" properties and methods in classical OOP.

Also, the variables number and suit live inside the instance but not as properties of the instance. They cannot be accessed via this because you didn't attach them. They act like "private variables" in classical OOP.

But since your getters are in the same scope (the constructor Card) as the variables, they have access to them, like the "getters" and "setters" of classical OOP.

function Card(n, s) {
  var number = n;
  var suit = s;
  //getters
  this.getNumber = function () {
    return number;
  };
  this.getSuit = function () {
    return suit;
  };
}
var test = new Card(10, 1);
test.getNumber();
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

You want

function Card(n,s) {
    this.number = n;
    this.suit = s;
}


    //getters
Card.prototype.getNumber =  function(){
        return this.number;
};
Card.prototype.getSuit = function(){
        return this.suit;
};

var test = new Card(10, 1);
test.getNumber();
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

The getters has to be member functions, ie it has to be defined on the this object.

In your case those getters are private to the constructor, it will not be accessible outside the constructor

function Card(n,s) {
    var number = n;
    var suit = s;
    //getters
    this.getNumber = function(){
            return this.number;
    };
    this.getSuit = function(){
            return this.suit;
    };
}
var test = new Card(10, 1);
test.getNumber();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531