简体   繁体   中英

How arguments are handled in Require JS define function

The following code is taken from a tutorial on the internet.

purchase.js

define(["credits","products"], function(credits,products) {

  console.log("Function : purchaseProduct");

  return {
    purchaseProduct: function() {

      var credit = credits.getCredits();
      if(credit > 0){
        products.reserveProduct();
        return true;
      }
      return false;
    }
  }
});

The second parameter of the define function is an anonymous function. This function takes two arguments, namely credits and products. These two arguments are used as objects in the code. How do these objects get assigned to those two parameters?

credits.js

define(function() {
  console.log("Function : getCredits");

  return {
    getCredits: function() {
      var credits = "100";
      return credits;
    }
  }
});

prodcts.js

define(function(product) {

  return {
    reserveProduct: function() { 
         console.log("Function : reserveProduct");
      return true;
    }
  }
});

When require() decides to call your anonymous "second parameter" function (which will happen when all dependencies are loaded) it will first look up the different modules you happened to ask for, using the string array in your first parameter. It then creates a matching array containing those actual module objects, as returned from those scripts, and uses that to call into your anonymous function.

If it helps understanding, sometimes my organization sees little runtime issues if someone happened to list one dependency in the wrong order, comparative to the anonymous function's arguments. (So if the anonymous function had the arguments in the opposite order, their assignments would be reversed and the code wouldn't work)

RequireJS will load the two files (misspelling on product.js filename) and they have anonymous functions that return objects. Those objects are then fed into the function.

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