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);