A function as an object in JavaScript. Code example open

A function as an object in JavaScript. Code example

In JavaScript, a function is also an object – a Function object and also has a prototype, properties, methods.

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

    var square = new Function('n', 'return n * n;');//n - function parameter, return n * n - the body of the function    
    console.log(square(2));//4

Properties of the Function object

The properties of the Function object include the following:

arguments – an array of arguments that are passed to the function
length – the number of arguments expected in the function
name – the name of the function prototype

Using the prototype, we can set additional properties to all functions:

    function display() {

        console.log("Hi");

    }

    Function.prototype.program = "No";

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

Method call

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

    function add(x, y) {
        return x + y;
    }

    var result = add.call(this, 3, 8);//this - in this case, the global window object. 3, 8 - the value of the function parameters

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

    function Person(name, age) {
        this.name = name;
        this.age = age;
    }

    var alex = new Person("Alexander", 33);


    function display() {
        console.log("Name " + this.name);
    }

    display.call(Person);//Name Alexander

In this case, only one value is passed because the display function takes no parameters. If we do not care about the object for which the function is called, then we can pass the null value:

    function add(x, y) {

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

    console.log(result); //11

Apply method

This method is similar to call(), which also calls a function, and as the first parameter also receives an object for which the function is called. The difference is that 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); // 11
0

More

Leave a Reply

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

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation