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
Post a Comment