// we are creating and calling a function that returns an object literal. // before returning it, we assign it to the variable "that". // JavaScript closures enable us to still reference "that" even after the function ended. // That way we always have a way to access our object reliably. var thistest = function() { var that = { string_one : 'Soylent Green', string_two : 'is People!!!', printOne : function() { console.log('Printing string one: ' + that.string_one); }, printTwo : function() { console.log('Printing string two: ' + that.string_two); }, printBoth : function() { that.printOne(); that.printTwo(); }, getViewer : function() { var req = opensocial.newDataRequest(); var params = {}; params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS]=[opensocial.Person.Field.GENDER, opensocial.Person.Field.PROFILE_URL]; req.add(req.newFetchPersonRequest("VIEWER", params), "viewer"); req.send(that.getViewerCallback); }, getViewerCallback: function() { //I don't care about the viewer data, just about what value "this" has console.log('in getViewerCallback'); console.log('this:'); console.log(this); console.log('that:'); console.log(that); that.printBoth(); }, runTest : function() { console.log('in runTest'); console.log('this:'); console.log(this); console.log('that:'); console.log(that); that.printBoth(); that.getViewer(); }, runOnLoadTest : function() { console.log('in runOnLoadTest'); console.log('this:'); console.log(this); console.log('that:'); console.log(that); that.printBoth(); that.getViewer(); } }; return that; }(); //notice that the function is invoked right away gadgets.util.registerOnLoadHandler(thistest.runOnLoadTest);

JavaScript this Test

This demo shows that the JavaScript 'this' object is not bound to what you'd expect if a method is called with registerOnLoadHandler, except if you use a closure. Watch your console.

(2008, Johannes Fahrenkrug)

]]>