user544079
user544079

Reputation: 16639

Using private members and methods in javascript

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

Upvotes: 0

Views: 38

Answers (3)

bvaughn
bvaughn

Reputation: 13497

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.

Upvotes: 0

errnesto
errnesto

Reputation: 832

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

Upvotes: 0

Josiah Keller
Josiah Keller

Reputation: 3675

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

Upvotes: 1

Related Questions