How "this" is looked up in callback of Javascript -


this question has answer here:

i have confused myself in following case:

function foo() { }  foo.prototype.bar1 = function() {   console.log(this); // shows "window"!! }  foo.prototype.bar2 = function(func) {   func(); }  var f = new foo(); f.bar2(f.bar1); 

how/why result of console.log(this) "window"? thought no matter how call public function of class here, "this" should refer "foo".

and right way avoid kind of error?

thanks

when f.bar2(f.bar1), you're passing reference of bar1 bar2; inside bar2, it's known "func", , connection f lost. the value of this determined dynamically when function invoked. if invoke f.bar1(), f, when invoke func(), it's undefined, , fall global object (window).

i have explained earlier follows:

the basic rules are, global object unless:

  • the function called object method (then object), or
  • the function called constructor, new operator (in case point new object being constructed)

one way avoid create bound function , pass that:

f.bar2(f.bar1.bind(f)); 

note function.prototype.bind not supported older browsers, might need polyfill (there's 1 available on mdn).

in simple scenario presented, can elclanrs suggests in comment, target available inside bar2:

func.call(this); 

Comments