Understanding JavaScript Methods
Methods in JavaScript are functions that are properties of objects. They allow objects to perform actions. Here's a quick example:
Exaple 1: Smartphone Object
const smartPhone ={ brand: "Google", model: "Pixel 9", displayTime(){ c console.log("The current time is displayed on the screen."); } }; smartPhone.displayTime
In this example:
- brand and model are properties.
- displaytime is a method that displays the current time.
Example 2: Letter Object
const letter = { toName: "Betty Johnson", toAddress: "1224 Main Street", fromName: "Charles Jones", fromAdress: "212 N. Park Ave", message: "Hello Betty, Please call me when you can, Chuck", print() { console.log("To Name: " + this.toName); console.log("To Address: " + this.toAddress); console.log("From Name: " + this.fromName); console.log("From Address: " + this.fromAdress); console.log("Message: " + this.message); } }; letter.print();
In this example:
- toName, toAddress, fromName, fromAdress, and message are properties of the letter object.
- print is a method that logs the details of the letter.
Methods in JavaScript help keep related functions within objects, making your code cleaner and more organized.