Advertisement
nher1625

higher_order_functions

May 18th, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Define an object with some properties and a method:
  2. var clientData = {
  3.     id: 094545,
  4.     newId: function() {
  5.         var id = "";
  6.         for (var idx in String(this.id)) {
  7.             id += String(Math.floor(Math.random()*10));
  8.         }
  9.         this.id = Number(id);
  10.     },
  11.     fullName: "Not Set",
  12.     // setUserName is a method on the clientData object
  13.     setUserName: function(firstName, lastName) {
  14.         // this refers to the fullName property in this object
  15.         this.fullName = firstName+" "+lastName;
  16.     }
  17. }
  18. function getUserInput(firstName, lastName, callback, callbackObj) {
  19.     // Do otherstuff tovalidate name here
  20.     // The use of the Apply function below will set the this object to be callbackObj
  21.     callback.apply(callbackObj, [firstName, lastName]);
  22. };
  23. // Pass the clientData.setUserName method and the clientData object as parameters.
  24. // The clientData object will be used by the Apply function to set the this object​
  25. getUserInput("Barack", "Obamanation", clientData.setUserName, clientData);
  26.  
  27. // the fullName property on the clientData was correctly set​
  28. console.log(clientData.fullName);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement