Guide – Call and Apply Functions

Guide – call and apply functions

Worth knowing

As you have probably heard in this class – in Javascript everything is an object.  Since everything is an object a function is an object. What does this mean?

When you write the Javascript

function myFunction(myArgument) {
  return "Congratulations";
}

You are creating a method of the window object. This does requires some knowledge of the document object model (DOM) – but let’s suffice it to say that anything you put on a web page belongs to an object either as a property or a method – including a function.

Calling a function – invoking a function as a function

Call a function is also called invoking a function – don’t get confused, they are the same thing. Javascript gives you multiple ways to do this and there are reasons to use them under different circumstances. The most common way of invoking a function is the simple line of code;

var result = myFunction(anArg);

which would be the same exact thing as 

var result = window.myFunction(anArg);

This is very creatively called invoking a function as a function.

Calling a function – invoking a function as a method

By now you should be able to create objects – here are 2 ways to create the same object. Don’t get confused – they do exactly the same thing (at least in as far as the structure of the object). The difference is the first method gives you a constructor function that allows you to build the object with arguments – a constructor

1.

function anObject() {
  this.aMethod = function() { return "Congratulations");
}
var myObject = new anObject(); 

2.

var myObject = {
    aMethod: function () {
        return “Congratulations”;
    }

Regardless of how you created anObject – you can invoke the function aMethod as a method of the object by using the call

var result = myObject.aMethod();

Using the call and apply methods

So if you didn’t have enough ways to invoke a method here are 2 more. The javascript Function object (note the caps to denote it is an object) has 2 built-in methods call and apply which also allow you to invoke a method. So lets return to our first function myFunction – we can also call the function by 

var result = myFunction.call(this, anArg);

the apply function requires the arguments be in an array – you”ll have to trust me, this can be quite handy

var args = [anArg];

var result = myFunction.apply(this, args);

This may seem convoluted, but it allows for the writing of dynamic code which can be quite useful – and also beyond the scope of this guide. There are some great examples on the web of using this to over-ride constructor behavior, which helps javascript become a little closer to a true object-oriented language. (it is not).