0

I know there are millions Q&As out there about "this", but still this is something that even after a lot of reading and thinking I still can't fathom. Consider this example:

(quoting "Javascript Patterns" by Setfanov)

var myapp = {};
myapp.color = "green"; 
myapp.paint = function (node) {
node.style.color = this.color; };

var findNodes = function (callback) { // ...
if (typeof callback === "function") {
callback(found); }
// ... };

... the object "this" will refer to the GLOBAL OBJECT, because findNodes() is a global function...

But shouldn't "this" be bound to who's calling it, in this case, the findNodes() function?

  • 2
    JavaScript binds `this` *when* the method is invoked. In this case it is *not* invoked 'on' an object so `this` will be window (or null, in some ES5/strict contexts). – user2864740 Sep 13 '16 at 04:10
  • 3
    Both the quote and your "but" are incorrect. Setting of `this` is based on how the function is called, not how or where it is defined. – nnnnnn Sep 13 '16 at 04:11
  • `this` is not bound to who is calling the method, but who the method is being called upon (e.g. `someTarget.someMethod()` ). – Thilo Sep 13 '16 at 04:11
  • @Thilo Enlightening! Thank you guys! – Yilei Zhang Sep 13 '16 at 04:25
  • @user2864740 Enlightening! Thank you guys! – Yilei Zhang Sep 13 '16 at 04:26
  • @Thilo—that's one case, there are other ways that a function's *this* is set (*new*, *bind*, *call*, *apply*, arrow functions, strict mode vs not strict). – RobG Sep 13 '16 at 05:17

0 Answers0