Q:

Confused with the variable in js

function Person(name){
    var age;
    this.name = name;
    this.setAge = function(a){
        age = a;
    }
    this.getAge = function(){
        return age;
    }
}
var p0 = new Person("John");
p0.setAge(24);
console.log("p0.getAge "+p0.getAge());//p0.getAge 24
var p1 = new Person("Mike")
p1.setAge("25");
console.log("p0.getAge "+p0.getAge());//I think the output here should be p0.getAge 25,but it is p0.getAge 24
console.log("p1.getAge "+p1.getAge());//p0.getAge 25

The variable "age" does not belong to any instance of Person as there is no "this.age" in the constructor of Person and it should be shared by instance of Person at first, But the result is not what i expected. I'm confused!

A:

function Person(name){
    var age;
    this.name = name;
    this.setAge = function(a){
        age = a;
    }
    this.getAge = function(){
        return age;
    }
}

look  var age;, you dont declare this.age, this is particularly done when you dont want variable directly accessed from outside, i.e. you try to make it private for that object, that is why you don't create a property for the object, but just a variable for that closure.
Still you can access it inside the object and return it using getAge method, but not directly with age. so there is no property age, but there exists a variable age

