简体   繁体   中英

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

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:

在此处输入图片说明

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.)

在此处输入图片说明

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.

在此处输入图片说明

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM