Hello I am a javascript beginner and I read about how to interpret the this keyword but in this example I am still confused:
<script> function example(param) { this.a = param; var b = true; this.getB = function() { return b; } this.setB = function(x) { b = x; } } document.write(window.a); //prints "undefined" (line A) document.write(window.b); //prints "undefined" (line B) document.write(window.getB(); //generates an error "undefined is not a function (Line C)" For Line A, I guess the explanation is that this refers to the object that owns the function example, in this case, the window object. Therefore you can reference window.a, but it is not defined so it prints undefined
I cannot understand Line B. Isn't var b restricting b to a local scope? Which should mean that you can only reference b within the function? I was expecting Line B to generate an error, not printing undefined.
I have totally no clue about Line C, why does it generate an error, and what does this mean in this case?
Many thanks!
thisdepends on how you call the function.new example().getB().example(). None of the code inside it gets executed.