Javascript "this" context when the callback is an object method -


i have 2 objects: myapp , dom. code on plunker taken (but little simplified) stoyan stefanov book "javascript patterns".

http://plnkr.co/edit/futgitmblnryfbkul0ig?p=preview

var myapp = {}; var color = "purple"; myapp.color = "green"; var dom = {}; dom.color = "red";  myapp.paint = function (node) {     console.log(this.color); };   dom.findnodes = function (callback) {     if (typeof callback === "function") {         callback();     } }   dom.findnodes(myapp.paint); 

according book:

if call findnodes(myapp.paint), won’t work expected, because this.color not defined. object refer global object, because findnodes() global function. if findnodes() method of object called dom (like dom.findnodes()), inside of callback refer dom instead of expected myapp.

on code expect color "red", because call object method dom.findnodes instead of global function. why global variable value "purple"? thanks!

this function:

function (callback) {     if (typeof callback === "function") {         callback();     } } 

… doesn't use this doesn't matter if call findnodes or dom.findnodes.

the this care here:

myapp.paint = function (node) {     console.log(this.color); }; 

when call myapp.paint(), this myapp.

when call callback(), this window (in browser, when not in strict mode).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -