Victor
Victor

Reputation: 17087

Benefits of using call keyword to call a function in Javascript

In JavaScript, we can call a function in two ways:

function f(message) { ... }
f.call(this, "test");

or just:

f("test")

Except that we can specify the scope in the first case, is there any other advantage to using this syntax over the other one?

Upvotes: 0

Views: 2193

Answers (3)

bfavaretto
bfavaretto

Reputation: 71918

You can also use call (and apply) for partial function application, which is when you create a function that calls another function with some preset arguments. For example:

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

// Function to create new adders with a preset 'a' argument
function createAdder(a) {
    return function(b) {
        return add.call(null, a, b);
    }
}

// Let's create a function that always adds five to what's passed in
var addFive = createAdder(5);

// Now let's test it
addFive(6); // 11 - it works!

Upvotes: 1

Kijewski
Kijewski

Reputation: 26022

You can pass a this object as you like/need. E.g.

[].slice.call("abcdef", 2) === ['c', 'd', 'e', 'f'];

or

var x = {hasOwnProperty:function() { return false; }, key:42};
x.hasOwnProperty('key'); // == false
{}.hasOwnProperty.call(x, 'key'); // true

You should take notice that call is not a keyword, but a method of Function.prototype.

Read:

Upvotes: 4

RobG
RobG

Reputation: 147363

Except that we can specify the scope in the first case

You can't "specify scope". Scope is set by how code is written, you can't dynamically change it other than to a limited extent using with. A function's this keyword has nothing to do with scope, it's always resolved as a local variable in the current execution context.

Upvotes: 3

Related Questions