Search code examples
javascriptvariablesprototypal-inheritance

Why is variable in prototypal constructor undefined when accessed as a property?


Why is myPerson.age undefined?

function Person() {
  var age = 28;
}

var myPerson = new Person();

console.log(myPerson.age);

I have clearly set what the varaible is in the Person function construtor which should be pointed to by the .prototype of myPerson, no?


Solution

  • Try this:

    function Person(){
    
        this.age = 28;
    
    }
    
    
    $(document).ready(function(){
    
    
      var myPerson = new Person();
    
      console.log(myPerson.age);
    
    
    });