Functions are First Class Citizens
Explore how JavaScript functions can be assigned as properties of objects and invoked like any other function. Understand dynamic function assignment within object instances. This lesson introduces function arguments and prepares you for more advanced function concepts to enhance your JavaScript skills.
We'll cover the following...
We'll cover the following...
Object instances in JavaScript can have properties that contain special objects, called functions.
After you assign a function to an object, you can use the corresponding property to invoke that function
This is shown in the Listing below:
Listing: Assigning functions to objects
<!DOCTYPE html>
<html>
<head>
<title>Functions</title>
<script>
// Define a constructor for Car
var Car = function (manuf, type, regno) {
this.manufacturer = manuf;
this.type = type;
this.regno = regno;
this.getHorsePower =
function () { return 97; }
}
// Create a Car
var car = new Car("Honda",
"FR-V", "ABC-123");
console.log("Horse power: " +
car.getHorsePower());
// It is a stronger car
car.getHorsePower =
function () { return 127; };
console.log("Horse power: " +
car.getHorsePower());
</script>
</head>
<body>
Listing 7-3: View the console output
</body>
</html>The ...