Javascript currying: why does one closure scope example work, but another doesn't?

134 views Asked by At

I'm trying to understand the video "Understanding Function Currying" on Vimeo ( http://vimeo.com/41238143 but not necessary to view it in order to understand this question).

The example I understand

Early in the video, We’re told that there’s a problem with this code:

enter image description here

The problem with this code: the use of callback on line 11 and 14 won’t work because it’s out of scope — onSuccess exists in the buildCRUD scope, not the create scope. (I'll call this the "callback example".)

OK, that makes sense to me. Solutions are considered including using a single class variable (I know this terminology is off because javascript doesn't have classes, but you know what I mean).

The example I don't understand

Here's where I'm confused. At the end of the video, we're told that this code for a different part of the function will work. (Notice the "className" variable parameter; I'll call this the "className example".)

(Sorry, I cut off the line that says "var ...", just trust me that it's up there and createFn, getFn, etc. are all being declared as part of a long "var" line.)

enter image description here

As you can see, the implementation of these functions such as createFn do use the className variable, though it wasn't passed into the function as a parameter.

enter image description here

Here's my question: why is className in scope inside createFn? It seems to me that it’s no more in the forClass scope than onSuccess was in the create scope.

Does this have something to do with...

  • the fact that the function in the callback example is never being assigned as a variable inside the create function context, only called?
  • the callback example using promises?
1

There are 1 answers

0
user2747330 On

My apologies everyone. The Vimeo recording may have had some errors.

To demonstrate a working solution, I created a working version of the Book CRUD service to demonstrate Partial Applications in JavaScript... used within an AngularJS application.

getFn = function (objectId, callback) {

      // Simulate $http to get book information for
      // specified ID.

      var deferred = $q.defer(),
          book = {
            url : buildRequestURL(objectId),
            title : "Learn to use Javascript Partial Applications"                
            author: "Thomas Burleson"
          },
          notifyFn = onSuccess(callback);


      $timeout(function() {
        notifyFn( book );
        deferred.resolve( book );
      });

      return deferred.promise;
}

@see Full Source & Live CodePen Demo