Javascript variable scope within onload function -
this question has answer here:
- what scope of variables in javascript? 21 answers
i had similar situation , curious why p
not know b
is, since p
defined within same function b
.
var = "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 } }();
you're accessing b
outside function declared in.
the local scope function-oriented.
so in:
window.onload = function() { var b = "b"; var p = new person(); p.doiknowaorb()' }
b
local variable anonymous (un-named) function connected onload.
but inside function doiknowaorb in p
:
person.prototype = function(){ function doiknowaorb() { console.log(a); console.log(b); }; return { "doiknowaorb": doiknowaorb } }();
there no b
. can access a
it's global variable.
Comments
Post a Comment