I have the following Javascript code;
var Person = function(name, age) {
this.name = name;
this.age = age;
return this;
};
Person.prototype.getAge = function() {
alert("Age : " + this.age);
}
var p1 = new Person("xyz",10);
p1.getAge();
This works perfectly and I get the alert as Age : 10
Now if I update the code as below (defined getAge() after instantiating Person object p1);
var Person = function(name, age) {
this.name = name;
this.age = age;
return this;
};
var p1 = new Person("xyz",10);
Person.prototype.getAge = function() {
alert("Age : " + this.age);
}
p1.getAge();
It still returns me the output as "Age : 10"
Now my question is how does this work correctly, since Person.prototype.getAge was defined after we have instantiated Person object p1 ? Is it because of the way "prototype" works ?