Question

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.

Was it helpful?

Solution

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

See window.name.

OTHER TIPS

You're not using prototype at all, it's better to put functions on the constructors prototype. For more info about constructor functions and prototype you can check out this answer.

As for why age is not logged; it's because you're trying to log window.age instead of p.age

p = new Person("Bob", 12);
console.log(p.name);
console.log(p.age);
console.log("this is:",this);
console.log("does window have a name property?",typeof this.name);
console.log("does window have an age property?",typeof this.age);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top