Functions can return values. But these values do not have to represent primitive data – numbers, strings, but can also be complex objects.
For example, let’s move the creation of the user object into a separate function:
function createUser(pName, pAge) {
return {
name: pName,
age:page,
displayInfo: function() {
document.write("Name: " + this.name + " age: " + this.age + "<br/>");
}
};
};
var tom = createUser("Tom", 26);
tom.displayInfo();
var alice = createUser("Alice", 24);
alice.displayInfo();
Here, the function createUser()takes the values pName and pAge and creates a new object from them, which is the returned result.
The advantage of moving object creation into a function is that we can then create several objects of the same type with different values.
In addition, an object can be passed as a parameter to a function:
function createUser(pName, pAge) {
return {
name: pName,
age:page,
displayInfo: function() {
document.write("Name: " + this.name + " age: " + this.age + "<br/>");
},
driveCar: function(car){
document.write(this.name + " drives " + car.name + "<br/>");
}
};
};
function createCar(mName, mYear){
return{
name: mName,
year: year
};
};
var tom = createUser("Tom", 26);
tom.displayInfo();
var bently = createCar("Bentley", 2004);
tom.driveCar(bently);
Two functions are used here to create users and a machine object. The driveCar()user object method takes a car object as a parameter.
As a result, the browser will display:
Name: Tom Age: 26
Tom is driving a Bentley