Objects in functions. JavaScript examples open

Objects in functions. JavaScript examples

Functions can return both simple values and complex ones, such as objects:

    function createUser(Name, Age) {
        return {
            name: Name,
            age: Age,
            displayInfo: function () {
                document.write("Name: " + this.name + " Age: " + this.age);
            }
        };
    };
    var person = createUser("Alexander", 33);

    person.displayInfo();
The advantage of moving the creation of an object into a function is that we can then create several objects of the same type with different meanings.

Objects can be passed as function parameters

Consider an example:

    function createUser(Name, Age) {
        return {
            name: Name,
            age: Age,
            displayInfo: function () {
                document.write("Name: " + this.name + " Age: " + this.age);
            },
            driveCar: function (car) {
                document.write(this.name + " drive car " + car.name);
            }
        };
    };

    function createCar(mName, mYear) {
        return {
            name: mName,
            year: mYear
        };
    };

    var person = createUser("Alexander", 33);
    person.displayInfo();

    var personcar = createCar("BMW", 2004);

    person.driveCar(personcar);
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