JavaScript Interview Question - Scoping

by jondlm

HTML

<div id="name_output"></div>
<div id="age_output"></div><!-- Why doesn't this work? -->

JavaScript

// Constructor
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// Methods
Person.prototype.getName = function() {
  return this.name;
}
Person.prototype.getAge = function() {
  return (function(){ return this.age; })();
}

// Instantiate
var sam = new Person('Sam Jenkins', 25);

// Output to HTML
document.querySelector('#name_output').innerText = sam.getName();
document.querySelector('#age_output').innerText = sam.getAge();