I'm sorry to ask such a basic question but despite lots of reading on javascript over the last few months and on this issue specifically, I'm just not getting something about it's execution context and "this". So I'm hoping an explanation using my specific scenario will help. I have a constructor in which I have some local functions and some exposed functions (mimicking public/private methods).
function blog() {
if (!(this instanceof blog))
return new blog();
function internal(){
alert(this);
}
this.external = function(){
alert(this);
internal();
}
}
var b = new blog();
b.external();
In external
, "this" is b, an instance of blog as I expect. I was wrongfully expecting this to hold true inside internal
as well, but it's actually the global window object. As an experiment I tried changing external
's call to this.internal()
which gives an error that this.internal is not a function. This is when I realized I'm really not following how it's working. Ok, I haven't defined a property of blog named internal, but if internal isn't a function defined on my blog instance, what is it and where is it defined? Maybe I have this structured wrong.