0

I had a similar situation to this and was curious why p does not know what b is, since p is defined within the same function as b.

var a = "a";
window.onload = function() {
    var b = "b";
    var p = new Person();
    p.doIknowAorB();

}
function Person() {
    this.name = "nate";
}
Person.prototype = function(){
    var doIknowAorB = function() {
        console.log(a);
        console.log(b);
    };
    return {
        "doIknowAorB": doIknowAorB
    }
}();
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
natecraft1
  • 2,737
  • 9
  • 36
  • 56
  • Prototyped methods are all about accessing properties on the object on which the method was invoked. There's no special relationship between prototyped methods and variable scope. The only variables they can access are the ones via typical lexical scope, and clearly `b` is in a scope not accessible to the function assigned to `doIknowAorB`. – cookie monster Jun 01 '14 at 05:31
  • I don't understand why b is "in a scope not accessibile to the function assigned to doIknowAorB".. I'm not a JS expert so I would like to understand this a bit – natecraft1 Jun 01 '14 at 05:44
  • The duplicate posted above will describe how variable scope works in JavaScript. This should be learned by reading a basic JavaScript tutorial. The only code that will be able to read the `b` variable will be the code inside the function where `b` was declared. This includes code in other functions nested inside that function. – cookie monster Jun 01 '14 at 05:50

2 Answers2

1

You're accessing b outside the function it was declared in.

The local scope is function-oriented.

so in:

window.onload = function() {
    var b = "b";
    var p = new Person();
    p.doIknowAorB()'
}

b is a local variable for the anonymous (un-named) function which is connected to onload.

but inside the function doIknowAorB in p:

Person.prototype = function(){
    function doIknowAorB() {
        console.log(a);
        console.log(b);
    };
    return {
        "doIknowAorB": doIknowAorB
    }
}();

There is obviously no b. You can access a as it's a global variable.

TastySpaceApple
  • 3,115
  • 1
  • 18
  • 27
0

Because b becomes a local variable or a private variable of the anonymous function.

Scope in javascript is function oriented.

So, it cannot be accessed outside that function block.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95