Javascript variable scope within onload function
This question already has an answer here:
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.
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.
上一篇: 为什么参数在函数外保留其值?