JavaScript Function as an object. call and apply methods

In JavaScript, a function is also an object – a Function object and also has a prototype, properties, methods. All functions that are used in a program are Function objects and have all of its properties and methods.

For example, we can create a function using the Function constructor:

var square = new Function('n', 'return n * n;');
console.log(square(5));

A number of parameters can be passed to the Function constructor. The last parameter is the function body itself as a string. Actually the string contains javascript code. The previous arguments contain the parameter names. In this case, the function of squaring a number is defined, which has one parameter n.

The properties of the Function object include the following:

  • arguments: array of arguments passed to the function
  • length: specifies the number of arguments the function expects
  • caller: specifies the function that called the currently executing function
  • name: function name
  • prototype: function prototype

With the help of the prototype, we can define additional properties:

display(){
    
    console.log("hello world");
}
Function.prototype.program ="Hello";

console.log(display.program); // Hello

Among the methods, the call() and apply() methods should be noted.

The call() method calls a function with the specified this value and arguments:

function add(x, y){
    
    return x + y;
}
var result = add.call(this, 3, 8);

console.log(result); // 11

This points to the object on which the function is called – in this case, the global window object. After this, the values ​​for the parameters are passed.

When passing an object via the first parameter, we can refer to it via this:

function User (name, age) {
    this.name = name;
    this.age = age;
}
var tom = new User("Том", 26);
function display(){
    console.log("Ваше имя: " + this.name);
}
display.call(tom); // Your name: Tom

In this case, only one value is passed because the display function takes no parameters. That is, the function will be called on the tom object.

If we do not care about the object for which the function is called, then we can pass null:

function add(x, y){
    
    return x + y;
}
var result = add.call(null, 3, 8);

console log(result); // eleven

Similar to a method is the apply() call() method , which also calls a function and also receives the object on which the function is called as its first parameter. Only now an array of arguments is passed as the second parameter:

function add(x, y){
    
    return x + y;
}
var result = add.apply(null, [3, 8]);

console log(result); // eleven