Review of JavaScript Invocation Patterns

JavaScript Invocation patterns can be tricky for developers new to the language. This tutorial will take a look and review the four different invocation patterns that JavaScript offers, and the behavior that is expected when using them.

A function invocation in JavaScript refers to passing control and parameters to another function during execution. This may not seem very interesting at first, but the functional ability that the developer can gain can be powerful.

If you have programmed in other languages, especially in many of the popular Object Oriented languages that contain the this parameter, you will quickly find that in JavaScript, the context execution of a function can change the functionality of a function in ways that are typically not expected.

Let’s dive into this in detail. Each function in JavaScript contains two implicit parameters, the this parameter that you use to call object properties with, and another parameter called the arguments parameter.

Along with these two implicit parameters, JavaScript also contains four different invocation patterns.


Let’s take a look.


The Four JavaScript Invocation Patterns:

  1. Constructor Invocation
  2. Function Invocation
  3. Method Invocation
  4. Apply Invocation


**Note: Each invocation pattern in JavaScript changes the initialization context of the this parameter.


Let’s take a look at how each pattern works.


The Constructor Invocation Pattern


Again, JavaScript is classless, prototypal inheritance language, but some of the syntax JavaScript uses camouflages its true nature. Some of JavaScript’s syntax makes the language appear to have classical inheritance, but it doesn’t.

When a function object in JavaScript is invoked with the new keyword, then that object is created with a “hidden link” to that function’s prototype member, and the this parameter will be bound to that new object.


Let’s take a look at an example.


Constructor Invocation Example:


// create a constructor function
// called HelloName
var HelloName = function(name) {
  this.say = name
};
// Give all instances of HelloName
// a public method called getSay
HelloName.prototype.getSay = function() {
  return this.say;
};
// create an instance of HelloName
var helloNameObj = new HelloName("Daryl");
// hello Daryl
console.log('hello' + helloNameObj.getSay());

When functions in JavaScript are created with the new keyword, they are called constructors. We add functionality to constructor functions by adding properties to the functions prototype.


**Note: By convention, the first letter of a constructor function is always capitalized.


Constructor functions in JavaScript can be very useful; however, using the “constructor style” method for creating functions is not recommended. JavaScript contains a better method built into the language, that accomplishes the same behavior. This method is to use Object.create, and we will look at why this is a better option later in another tutorial.


The Function Invocation Pattern


A function is not a property of an object when the function is invoked using the Function Invocation Pattern. If the function is invoked with this pattern, the this parameter becomes bound to the global object, and this can become a problem.


**Note: This was considered a design flaw when the language was developed, because binding to the global object is bad. We won’t go into complete detail of why it is bad in this tutorial, but we will look at a commonly used example of why. There are a lot of reasons, so just trust me (or Google it), binding globally is a nightmare waiting to happen.. 😛


OK, let’s first take a look at the Function Invocation Pattern, and then since binding to the global object is bad, we’ll take a look at how a standardized work around is implemented when a function is invoked inside a method.

Function Invocation Example:


// invoked as a function
var addTogether = add(1, 2); // 3
// using our helloNameObj object
// modify helloNameObj to contain a
// moneyMakerAlgorithm method
var helloNameObj.moneyMakerAlgorithm = function() { 
  var that = this; // work around
  var extraMathProcessing = function() {
    // "that" holds the correct "this" value now
    that.value = add(that.value, that.value);
  }
  // invoke as a function
  extraMathProcessing(); // "this" is now bound to global object
}
// invoke moneyMakerAlgorithm as a method
helloNameObj.moneyMakerAlgorithm();
// output result of value
console.log(helloNameObj.value);


The Method Invocation Pattern


As mentioned, when a function is stored as a property of an object, that property is called a method. When a method is invoked, the this parameter is bound to that method, and that method is a function object.


Let’s take a look at an example.


Method Invocation Example:


// create an object literal with 
// a method. The input param is
// optional, but there should be
// validation checking for if input
// is actually of data type number
var helloNameObj = { 
  value: 1,
  increase: function(num){
    this.value += num;
  }
};
helloNameObj.increase(1); // value = 2
helloNameObj.increase(3); // value = 5


The Apply Invocation Pattern


Since JavaScript supports a functional programming paradigm, then functions can be “first-class citizens”, and since functions are objects, then functions can contain other functions, called methods.

The implications of these features are that JavaScript contains an “Apply Invocation pattern”. This pattern, enables the creation of an array of arguments that can be invoked on a function directly. When doing this, we can apply the context of the this parameter to the context of our choosing.


Let’s take a look at some examples.


Apply Invocation Example:


// apply takes two parameters
// first - is the this parameter
// second - is the array of arguments
// to apply on the function
var helloNameArr = [2, 3];
var addTogether = add.apply(null, helloNameArr); // 5

Apply Invocation Example:


// create an object literal with a 
// say property like in the constructor
// invocation pattern
var helloNameObj {
  say: 'hello Daryl'
};
// Unlike above in the constructor
// invocation pattern, helloNameObj
// does not inherit from 
// HelloName.prototype, so
// we do not have a getSay method
// on helloNameObj, but we can
// invoke getSay on helloNameObj
// by using the apply keyword again
var say = HelloName.prototype.getSay.apply(helloNameObj);
// hello Daryl



Now that we went through all the invocation patterns, let’s take a look at an interesting array parameter that JavaScript makes available.


JavaScript Arguments Parameter



JavaScript contains an array parameter, that is implicitly available to functions when they are invoked. The arguments array allows functions to be invoked with extra arguments. This includes ones that are not already defined as the functions parameters. The implications of this, is that functions can be invoked with an unspecified number of arguments.

Let’s take a look.

Arguments Parameter Example:


// invoked as a function
var addStuff = function() {
  var result=0; 
  for(var i=0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
console.log(addStuff(1,2,3); // 6


And that's it for the JavaScript invocation review.
Happy coding 😀


Proxy Node.js Application Requests through Apache

Running a Node.js application along side other non node web applications can work well if configured correctly. This tutorial will show you how to easily configure a Virtual Host to proxy Node.js application requests through Apache.


First, we need to make sure that we have Node.js running on a port other than the port Apache is running on (usually port 80). Our goal is to run the Node.js server on a port other than 80, and then use Apache to proxy incoming Node.js application requests to the port that the Node.js server is running on.


First, we need to make sure that Apache has the mod_proxy.so and mod_proxy_http.so modules loaded. If they are not loaded, go uncomment them in the Apache configuration file, and then restart the server.

Next, we need to configure an Apache Virtual Host just like we would any other VHost, except we want to proxy all domain requests for your Node.js application to the Node.js server.


**Note: The process is also the same if only a portion of an application is using Node.js.


Let’s take a look.

Apache Virtual Host for the Node.js Application



    ServerName www.yoursite.com
    ServerAlias yoursite.com
    DocumentRoot /your/site/location
    ErrorLog logs/yoursite.com-error_log
    CustomLog logs/yoursite.com-access_log common

    ProxyRequests off
    
        Order deny,allow
        Allow from all
    
    
        ProxyPass http://127.0.0.1:3000/
        ProxyPassReverse http://127.0.0.1:3000/
    




**Note: This configuration assumes that the node.js server is already running locally on port 3000, but it could be configured to use any unused port and/or an IP, that points to a system that is not the same as the one that Apache is running on.


Next, we need to tell Apache to proxy all node.js requests to node.js. This is done in our location directive with ProxyPass. All domain requests for www.yoursite.com will proxy to the node.js server running locally on port 3000.

Our ProxyPassReverse is used if/when our application performs a redirect, however its usually good practice to add even if your application isn’t redirecting.

For example, if our Virtual Host proxies incoming requests to our node.js application running at localhost on port 3000, and if our application performs a HTTP 301 or 302 redirect for one of those requests, there we be an error.

Our response headers will contain a location of http://127.0.0.1:3000/your/site/location/redirected-location when sent back to Apache.

And as you can tell, if Apache sends this location back to the client, then there will more than likely be an error.


ProxyPassReverse solves this by rewriting the location in our response headers so that Apache sends yoursite.com/redirected-location back to the client’s browser.


After that, save your Virtual Host configuration for your node.js application, and restart Apache.


And that’s it!

All incoming requests to yoursite.com should now be proxied to your node.js application.


Happy Coding! 😀

JavaScript Async and Callbacks versus Promises

JavaScript Async & Callbacks

Asynchronous calls and callbacks are how JavaScript is able to respond to user events that occur after the browser has loaded the DOM. This type of programming is commonly referred to as event-driven programming.

In event-driven programming, once an event occurs, its registered callback to that event fires off its functionality. An event could occur from many varying incidents, such as removing an input field from a web form, or retrieving data from a remote web service.

Let’s take a look

Async call with a Callback


// get data from remote url
getJSON(url, function(err, data){
  // check for errors
  // no errors - process data
  // check data condition
  // check another condition
  // else do this condition
});

The data returned from calling our remote web service, fires the callback function with either the data or an error returned as a dynamic argument.

Using a callback for a simple event is fine. However, if an event contains multiple conditions that need to be checked, then callback functions can become hard to read and maintain. In these more complex cases, JavaScript Promises are the solution.


JavaScript Promises
JavaScript promises are considered a best practice when “calling back”. Promises make callback functionality easier to read by eliminating the need for convoluted error and data conditional checking.

The reason is due to a specific condition will not fire, unless it occurs.

Let’s take a look

Async Using a Promise


// our promise
var promiseData = getRemoteData(url);

promiseData.then(function(data){
  // do something interesting
  // with the returned data  
});

We create a promise variable named promiseData and then call the remote web service like before.


JavaScript promises have a then method defined on them, and this is the location where we create our callback functionality.


If any side effects occur, such as an error, we don’t have to check for this condition, because our then method will only fire the callback if the data is returned. If the data does not return, the then method never executes.


And that’s it! There’s obviously a million other examples between the two, but this gives an simple clear cut practical solution on why you would use promises.

Happy coding! 😀