In JavaScript, functions are first-class citizens, which means they are objects and can have their own methods. Two such powerful methods are call and apply, both available through Function.prototype.

Understanding call()

Let’s start with a simple example:

function add(a, b) {
    return a + b;
}

console.log(add(1, 2));            // 3
console.log(add.call(this, 1, 2)); // 3

The call() method allows you to invoke a function and explicitly set the value of this. The first argument to call is the value you want this to be, and the rest are passed as normal arguments to the function.

How this Works in Methods

var palestrina = {
    work: "Missa Papae Marcelli",
    describe: function() {
        console.log(this.work);
    }
};

palestrina.describe(); // "Missa Papae Marcelli"

But what if you want to use describe for another object? Enter call():

var erasmus = {
    work: "Freedom of the Will"
};

palestrina.describe.call(erasmus); // "Freedom of the Will"

This is useful when borrowing methods from one object for use in another.

Borrowing Array Methods

This technique also comes in handy with array-like objects:

function myFunc() {
    var args = Array.prototype.slice.call(arguments);
}

You can even apply array methods to strings:

var original = "There is 1 number.";

var updated = Array.prototype.filter.call(original, function(val) {
    return val.match(/1/);
});

console.log(updated);       // ["1"]
console.log(updated.join('')); // "1"

The Difference with apply()

Now let’s talk about apply(). It’s nearly identical to call(), except it takes an array of arguments instead of individual ones:

function add(a, b) {
    return a + b;
}

console.log(add.call(this, 1, 2));       // 3
console.log(add.apply(this, [1, 2]));    // 3

This makes apply() especially powerful when working with dynamic or variable-length argument lists.

Conclusion

Both call() and apply() give you fine-grained control over how functions are executed and what this refers to. While call() is great for fixed arguments, apply() shines when dealing with arrays. Mastering them both is key to writing flexible and powerful JavaScript.

Post a Comment

Your email address will not be published. Required fields are marked *