JavaScript Methods

This tutorial is part of a web programming course for people who have no programming experience.


In the previous lesson we discussed how objects in JavaScript allow us to simulate the properties of real world objects. Objects in JavaScript 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 bread, 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.

Let's consider what a dog object could look like if we start adding behaviors:

var dog = {
  name:  "Lassie",
  breed: "Border Collie",
  bark: function(){
    alert("Ruff!");
  },
  eat: function(amount){
    console.log("Just ate this much: " + amount);
  }
};

It takes a little bit of getting used to to sort through this syntax. What we have done is added two new properties, bark, and eat. The values of the new properties are functions that simulate the behavior of a dog.

If an object has properties that are functions, we can invoke the functions by using the dot operator, just as we do when access other properties of an object. The difference is that we must add the parenthesis () in order to invoke the method. Recall that when we invoke functions, we put () after the function name.

// to call/invoke a method of an object, you can do it like this:
dog.bark();
dog.eat(10);

When properties of objects happen to be functions, they are called methods. As a quick side note, notice that the color coding in the code sample can help you identify functions and methods. Sublime Text (the tool we have been using in this course) also colors the code to help you read and understand it.

Using the Dot Operator to Add Methods to an Object

There are various ways you can go about creating objects (and adding methods to them). In the first code sample, when we declared the dog object, we put put all the details right inside the curly braces that enclose the object. But we can also start with an empty object and build it up by using the dot operator. You saw in the previous lesson how you can write a statement that creates and empty object, and then adds properties in subsequent statements. You can add methods in this way as well:

// create an empty object
var dog = {};

// add some properties to the object
dog.name = "Lassie";
dog.breed = "Border Collie";

// add a method
dog.eat = function(amount){
  console.log("Just ate this much: " + amount);
};

Accessing properties from within Methods

Methods can access other properties inside the object, in order to do so, you have to use the this keyword, followed by the dot operator, followed by the name of the property that you wish to acess. Consider this object that simulates an purchase order:

var purchaseOrder = {

  customerName: "Bob Smith",
  productName: "Bicycle",
  productPrice: 199.95,
  taxRate: 0.05,
  printReceipt: function(){
  	
  	// Add the taxes
  	var 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)
  }
};

// let's invoke the printReceipt() method of the purchase order
purchaseOrder.printReceipt();

Suddenly our objects are beginning to look quite complicated. And objects in real world applications can be extremely complicated. In some programming languages, like Java, entire applications are bundled into a single object.

By now you know that I am always ranting about formatting your code with proper indentation. Notice that all the lines of code within the body printReceipt method are indented.

Beginning students will often forget to include this when trying to access a property from within a method.

I've mentioned that we have been simulating real world objects in our code. But that's not entirely true. If you think about it, a purchase order is not a phyical thing (although it's details are often printed on paper), instead it's an agreement. Likewise, an email is not a physical thing that you can touch and hold. But you can conceptualize properties, such as 'to', 'from', and 'subject'. A method of an email object might be 'send' which delivers it to the recipient's mail server. I like to call these kinds of objects virtual objects. You will work with virtual objects often in your programming career, some other examples are files and folders on a computer, and dates. In the upcomming lessons you will see how a web page is loaded with objects, all of which you can manipulate with your JavaScript code.

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. It's complicated, and there are many different ways to go about it. In JavaScript there are all sorts of ways you can go about simulating and creating objects (most of them are better than what I showed you in this lesson). The approach that I am taking in this course is one that will hopefully set you up to understand object in Java and C# (my students go on into those courses after completing this one).

NEXT LESSON: DOM Objects