Search code examples
javascriptoopscopereferenceerror

Javascript OOP - Why do these two almost exact same statements give different outputs?


So I'm new to 'proper' Javascript programming as a whole. I've only ever really used it for simple DOM manipulations with a bit of dabbling in jQuery. Now I'm trying to learn the full concepts of programming in Javascript including OOP and the like. I liked to think I understood a fair bit about scope in JS, but I can't understand this:

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

    this.getName = function(){
        return name;
    }

    this.setName = function(name){
        this.name = name;
    }

    this.getAge = function(){
        return age;
    }

    this.setAge = function(age){
        this.age = age;
    }
}

p = new Person("Bob", 12);
console.log(p.getName());
console.log(p.getAge());

console.log(name);  //logs "an empty string" - What?
console.log(age);   //logs "ReferenceError: age is not defined" - Expected

After the first two console.logs came out fine, I wanted to check the values of the properties within the Person function to make sure nothing had fallen out of scope. name had to some extent (only gave an empty value - but still existed), but age hadn't.

I can't see any typos, which is the only thing I would've understood causing this issue. So why does console.log(name); not give a ReferenceError?

As much as I'd like to just know the answer, I'd really appreciate a full explanation of the root issue, including any key terminology such as prototypes, lexical scope, hoisting etc.


Solution

  • The name identifier exists in browsers' global scope, it's a property of the window.

    See window.name.