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

1
  • 2
    What you describe as "private members" are simple local variables. You won't be able to access them using this. Read stackoverflow.com/q/13418669/1048572 Commented Feb 27, 2015 at 0:58

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.