0
var test = function(id, company){
    //public members
    this.id = id;
    this.company = company;
    //private member
    var age = 24;
    //private method
    var getAge = function(){
       return this.age;
    };
    //public method
    this.displayAge = function(){
       console.log(getAge());
    }
}

//invoking 

var t = new test(1, 'XYZ Corp');

t.displayAge(); //undefined

Why is it not getting displayed

user544079
  • 16,109
  • 42
  • 115
  • 171
  • 2
    What you describe as "private members" are simple *local variables*. You won't be able to access them using `this`. Read http://stackoverflow.com/q/13418669/1048572 – Bergi Feb 27 '15 at 00:58

3 Answers3

1

It's not being displayed because this.age is undefined. You want age.

Josiah Keller
  • 3,635
  • 3
  • 23
  • 35
0

Because of the scope of variables in js

A variable is visible inside a function not outside

var a = "foo"
function fooBar () {
  var b = "bar"
  console.log(a) // foo
  console.log(b) // bar
}

console.log(a) // foo
console.log(b) // undefined
errnesto
  • 822
  • 5
  • 15
0

You want this:

var test = function(id, company){
    //public members
    this.id = id;
    this.company = company;
    //private member
    var age = 24;
    //private method
    this.getAge = function(){
       return age;
    };
    //public method
    this.displayAge = function(){
       console.log(this.getAge());
    }
}

//invoking 

var t = new test(1, 'XYZ Corp');

t.displayAge(); //undefined

Note that both "getAge" and "displayAge" need to be attached to this but your private variable "age" should not be.

bvaughn
  • 13,300
  • 45
  • 46