Methods
This lesson is part of the Web Programming 1 Course.
In the previous lesson we discussed how objects in JavaScript allow us to simulate the properties of real world objects. Objects in programming can also be used to simulate the behavior of real-world objects. We spent a good deal of our time in the last lesson simulating the properties of a dog object. Dogs not only have properties, such as breed, age, weight, they also have behaviors. They bark, walk, eat, sleep, etc. In order to simulate these behaviors in our programs, we can add functions to our dog objects.
This is what a dog object might look like if we start adding functions that simulate dog behaviors:
const dog = {
name: "Lassie",
breed: "Border Collie",
bark: function(){
alert("Ruff!");
},
eat: function(amount){
console.log("Just ate this much: " + amount);
}
};
Note that this object has 4 properties, two of them are strings (name and breed), and the other two are functions (bark and eat).
When you add functions to an object like this, we no longer call them 'functions'. Instead we call them methods. A method is a function that is defined inside of an object. Methods are used to simulate behaviors of real-world objects.
To invoke/call a method, you must must type in the name of the variable that is storing the object, followed by the dot operator, then the method name with parenthesis.
This is how we can call/invoke the methods of our dog object:
dog.bark();
dog.eat(10);
Note that the eat method has a parameter, that represents how much the dog is eating (although it's not clear if the parameter represents biscuits, or pounds, etc.).
Modern Syntax for Adding Methods to Objects
There is an alternative syntax for adding methods to objects that you should be aware of:
const dog = {
name: "Lassie",
breed: "Border Collie",
bark(){
alert("Ruff!");
},
eat(amount){
console.log("Just ate this much: " + amount);
}
};
This is very similar to the original version of our dog object variable. The only difference is that the colon (:) the the function keyword have been removed.
Function Calls vs Method Calls
When you look at code, you can tell when a function is being called vs a method because a method call must start with the object variable (like the dog variable we've been using) followed by the dot operator, then the method name and parenthesis.
Can you tell which of these two calls is a 'method call' and which is a 'function call'?
email.send();
calculateTotal(price);
I suppose that, technically, you could say that both are function calls (because a method is a type of function - one that is built into an object). But I want you to start to recognize when a method is being called. In the above code sample, the send method is preceded by a variable named email that presumably stores an object.
Here's another example:
alert("Hello!");
console.log("Hello!");
In this case log is a method that is being called/invoked on the console object. The console is an object that is built into the browser, and it represents the console window that you see when you open the browsers Web Developer Tools. It has various properties and methods. Note that you could consider the console a 'virtual' object because it is not something that really exists. Instead, it is imagery that is painted into your monitor screen by your browser when you open the Developer Tools.
Accessing Properties from within Methods
Methods can access other properties inside the object. But in order to do so, you have to use the this keyword, followed by the dot operator, and then the name of the property that you wish to access. Consider an object that simulates a purchase order:
const purchaseOrder = {
customerName: "Bob Smith",
productName: "Bicycle",
productPrice: 199.95,
taxRate: 0.05,
printReceipt(){
// calculate the total price
const totalPrice = this.productPrice * (1 + this.taxRate);
// print the receipt
console.log("CUSTOMER: " + this.customerName);
console.log("PRODUCT: " + this.productName);
console.log("PRICE: " + this.productPrice);
console.log("TOTAL:" + totalPrice); // NOTE - we don't use 'this.' for the totalPrice
}
};
// invoke the printReceipt() method of the purchaseOrder object
purchaseOrder.printReceipt();
Look at the body of the printReceipt method, and note that it's making use of the following properties of the object: productPrice, taxRate, customerName, and productName. Now note that within the method body, each of these properties has been preceded with this.. In a method body, you must include this. when referring to properties of the same object. I'm not exactly sure why this is required, but if you don't then JavaScript assumes you are referring to global variables (remember our discussion of variable scope).
Beginning students will often forget to include this. when trying to access a property from within a method body.
Summary
We are starting to dig in to object-oriented programming, which is a huge topic. Many programmers spend years, if not entire careers trying to understand the ins and outs of object-oriented programming. For us, this is just the beginning!