in order to declare publicly accessible function inside JavaScript object you have to use this
. By applying this
you actually expose this function as a property of an object
function Person(first,last) {
this.firstname = first;
this.lastname = last;
//private variable available only for person internal use
var age = 25;
//private function available only for person internal use
var returnAge = function() {
return age;
};
// public function available as person propert
this.askAge = function()
{
return returnAge ;
}
}
var john = new Person('John','Smith');
console.log(john.returnAge); // will return undefined
var johnsAge = john.askAge(); // will return 25