I thought I understood the constructors and prototypes in javascript until I wrote this code and got unexpected results...
function Person() {
var age = 18;
Person.prototype.getAge = function() {
return age;
};
Person.prototype.setAge = function(value) {
age = value;
}
this.getAge1 = function() {
return age;
};
this.setAge1 = function(value) {
age = value;
}
};
var marry = new Person();
var jack = new Person();
console.log(marry.getAge()); //output 18
console.log(jack.getAge()); //output 18
console.log(marry.getAge1()); //output 18
console.log(jack.getAge1()); //output 18
marry = new Person();
jack = new Person();
marry.setAge(22);
console.log(marry.getAge()); //output 22
console.log(jack.getAge()); //output 22
console.log(marry.getAge1()); //output 18
console.log(jack.getAge1()); //output 22
marry = new Person();
jack = new Person();
jack.setAge(22);
console.log(marry.getAge()); //output 22
console.log(jack.getAge()); //output 22
console.log(marry.getAge1()); //output 18
console.log(jack.getAge1()); //outputv 22
marry = new Person();
jack = new Person();
marry.setAge1(22);
console.log(marry.getAge()); //output 18
console.log(jack.getAge()); //output 18
console.log(marry.getAge1()); //output 22
console.log(jack.getAge1()); //output 18
marry = new Person();
jack = new Person();
jack.setAge1(22);
console.log(marry.getAge()); //output 22
console.log(jack.getAge()); //output 22
console.log(marry.getAge1()); //output 18
console.log(jack.getAge1()); //output 22
why I get same outputs after calling marry.setAge(22) and jack.setAge(22)?
why I get different outputs after calling marry.setAge1(22) and jack.setAge(22)?
Is the variable age Shared by the objects(jack and marry)?